package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.escalation.dao.EscalationOrderTDao;
import com.cci.kangdao.model.WorkOrderInfo;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.WorkOrderListService;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Service("WorkOrderListService")
public class WorkOrderListServiceImpl implements WorkOrderListService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private WorkOrderListDao workOrderListDao;

    @Resource
    private PropertiesUtils propertiesUtils;

    @Resource
    private LoginDao loginDao;

    @Resource
    private WorkOrderTDao workOrderTDao;

    @Resource
    private UserTDao userTDao;

    @Resource
    private CompanyTDao companyTDao;

    @Resource
    private WorkOrderRemedyPictureDao workOrderRemedyPictureDao;

    @Resource
    private BusinessRegionTDao businessRegionTDao;
    @Resource
    private RolesTDao rolesTDao;

    @Resource
    private ServiceStationDao serviceStationDao;

    @Autowired
    private WorkOrderOperatorRelationDao workOrderOperatorRelationDao;

    @Resource
    private WorkOrderFlowTDao workOrderFlowTDao;

    @Resource
    private WorkOrderDrDao workOrderDrDao;
    @Resource
    private DictionariesTDao dictionariesTDao;
    @Resource
    private DiagnoseConclusionTDao diagnoseConclusionTDao;
    @Resource
    private TechDealWithWorkOrderDao techDealWithWorkOrderDao;
    @Resource
    private EscalationOrderTDao escalationOrderTDao;
    @Resource
    private WorkOrderPrincipalTDao workOrderPrincipalTDao;
    @Resource
    private AppVersionTDao appVersionTDao;
    @Resource
    private EngineMsgDao engineMsgDao;
    @Resource
    private EngineMasterDataMapper engineMasterDataMapper;

    private static final String  OCRURL = "OCRURL";

    @Override
    public ModelAndView getCollectionList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //查看是否缺少必要参数
            if ("".equals(MapUtils.getString(map, "UserId", ""))
                    || "".equals(MapUtils.getString(map, "RoleType", ""))) {
                obj.put("status", SMSEnum.type17.getIndex());
                obj.put("msg", SMSEnum.type17.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
            //获取ccec在企业表中主键id
            int roleType = MapUtils.getIntValue(map, "RoleType"); // 字典项   在下面逻辑做转换使用
            CompanyT ccecCompany = companyTDao.getCompanyInfoByCompanyNo("CCEC");
            map.put("ccecCompanyId", ccecCompany.getId());
            //转换登录用户Id
            String UserId = map.get("UserId").toString();
            UserT userT = loginDao.getUserByid(UserId);
            long lUserId = userT.getId();
            map.put("UserId", lUserId);
            String eAppVersion = MapUtils.getString(map,"eAppVersion");
            //最终用户查询工单时，部分工单状态需要隐藏，读取查询用户类型字典
            map.put("customerRoleId", Dictionaries.roleType_01.getIndex());
            map.put("servicestationRoleId", Dictionaries.roleType_03.getIndex());
            //处理查询参数
            if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                map.remove("keyword");
            } else {
                if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                    String keyWord = map.get("keyword").toString().trim();
                    map.put("keyword", keyWord);
                }
            }
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//                page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //获取系统当前时间
            map.put("nowTime", LocalTimeUtil.getRealCurrentTime());
            //工单状态字典列表
            List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
            String dbuStatusCheck = appVersionTDao.getVersionCompatible("dbuStatusCheck");
            //分页处理，显示第一页的10条数据
            PageHelper.startPage(page, pagesize);
            //查询列表数据
            List<WorkOrderInfo> collectionList = workOrderListDao.getCollectionList(map);

            handleFieldsNew(collectionList);


            //循环处理查询列表（审核不通过、已取消、异常关闭、待用户评价 这几种情况下，处理时长=这几种动作发生时间-工单生成时间）
            if (CollectionUtils.isNotEmpty(collectionList)) {
                List<Long> orderIdList = collectionList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                //服务站关系类型
                List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);
                //获取主动升级工单
                List<WorkOrderInfo> escalationList = escalationOrderTDao.getEscalationByOrderIdList(orderIdList);

                for(WorkOrderInfo result : collectionList) {
                    if (StringUtils.isEmpty(result.getRealESN())) {
                        result.setRealESN(result.getESN());
                    }
                    //状态转换
                    int orderStatusNo = result.getOrderStatusNo();
                    Integer[] statusAttr = new Integer[]{2,3,5,18,20,23,24,33};
                    List<Integer> statusList = Arrays.asList(statusAttr);
                    if(roleType == MapUtils.getInteger(map, "customerRoleId")){
                        if(statusList.contains(orderStatusNo)){
                            orderStatusNo = 4;
                        } else if(orderStatusNo == 3){
                            if(result.getTransferReason().contains("用户不需要维修")){
                                orderStatusNo = 15;
                            } else {
                                orderStatusNo = 4;
                            }
                        } else if(orderStatusNo == 9){
                            orderStatusNo = 7;
                        } else if(orderStatusNo == 31){
                            orderStatusNo = 16;
                        } else if(orderStatusNo == 40 && (StringUtils.isBlank(eAppVersion) || eAppVersion.compareTo(dbuStatusCheck) < 0)){
                            orderStatusNo = 1;
                        }
                    }
                    if(orderStatusNo == 21){
                        orderStatusNo = 16;
                    } else if(orderStatusNo == 30){
                        orderStatusNo = 15;
                    }
                    for(DictionariesT dict : orderStatusList){
                        if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                            result.setOrderStatus(dict.getDvalue());
                        }
                    }
                    if(result.getOrderChannel() == 4 && result.getIsTechSupport() == 1 && orderStatusNo ==  2){
                        result.setOrderStatus("待大区经理确认");
                    }
                    //服务站关系类型
                    boolean isPrin = false;
                    for (Long orderId : principalList) {
                        if (result.getOrderId().equals(orderId)) {
                            isPrin = true;
                        }
                    }
                    if (isPrin) {
                        if (!result.getStationRelationType().equals(2)) {
                            result.setStationRelationType(1);
                        }
                    } else {
                        result.setStationRelationType(0);
                    }
                    //获取主动升级工单
                    for(WorkOrderInfo favorate : escalationList){
                        if(result.getOrderId().equals(favorate.getOrderId())){
                            result.setEscalationOrderID(favorate.getId());
                        }
                    }

                    Integer OrderStatus = result.getOrderStatusNo();
                    long OrderChannel = result.getOrderChannel();
                    if (OrderChannel == ccecCompany.getId() && (roleType == 1 || roleType == 3)) { //ccec渠道   用户和站长查看收藏列表时   400审核不通过  前端展示待更新
                        if (25 == OrderStatus) { //工单来源是用户报单的并且状态为ccec400审核不通过的   工单状态显示待更新
                            result.setOrderStatus("待更新");
                        }
                    }
                    if (null != OrderStatus) {
                        //审核不通过
                        if (OrderStatus.equals(3) || OrderStatus.equals(15)
                                || OrderStatus.equals(13) || OrderStatus.equals(16)
                                || OrderStatus.equals(5) || OrderStatus.equals(14)
                                || OrderStatus.equals(28) || OrderStatus.equals(29)
                                || OrderStatus.equals(30) || OrderStatus.equals(31)
                                || OrderStatus.equals(39)) {
                            long dealTime = Date_Util.getSubTime(result.getCreateTime(), result.getDealTiming(), 1);
                            if (dealTime == -1) {
                                result.setDealTime(0L);
                            } else {
                                result.setDealTime(dealTime);
                            }
                        }
                    }
                }
            }

            /**
             * 3.1.0 4.2需求修改了DBU、XCEC服务工单技师维修完成后显示的处理时长
             */
            try {
                addHandleTimeNew(collectionList);
            } catch (Exception e) {
                log.error("getCollectionList->服务工单处理时长异常", e);
            }

            long et = System.currentTimeMillis() - st;
            log.info(String.format("获取工单收藏列表响应消耗时间: %d", et));
            //返回数据
            JSONObject jb = new JSONObject();
            PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(collectionList);
            jb.put("functions", JSON.toJSON(pageInfo.getList()));
            obj.put("status", SMSEnum.type0.getIndex());
            obj.put("msg", SMSEnum.type0.getName());
            obj.put("data", jb);
            //返回客户
            ParameterTool.writeResponse(response, obj.toString());
            obj = null;
            return null;
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            obj = null;
            return null;
        }
    }


    //收藏或取消收藏
    @Override
    public ModelAndView setUpCollection(Map<String, Object> map) {
        // TODO Auto-generated method stub
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //设置结果
            int result = -1;
            //转换登录用户Id
            String UserId = map.get("UserId").toString();
            long lUserId = loginDao.getUserByid(UserId).getId();
            map.put("UserId", lUserId);
            //查看是否缺少必要参数
            if ("".equals(MapUtils.getString(map, "OrderId", "")) || "".equals(MapUtils.getString(map, "isCollect", ""))
                    || "".equals(MapUtils.getString(map, "UserId", ""))) {
                obj.put("status", SMSEnum.type17.getIndex());
                obj.put("msg", SMSEnum.type17.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
            //查看该账户与该工单目前的关联状态
            Map<String, Object> existMap = new HashMap<String, Object>();
            existMap = workOrderListDao.getCollectionStatus(map);
            //判断是设置收藏还是取消收藏
            if ("1".equals(map.get("isCollect").toString())) {
                //设置收藏
                if (null != existMap && existMap.size() > 0) {
                    obj.put("status", SMSEnum.type26.getIndex());
                    obj.put("msg", SMSEnum.type26.getName());
                    obj.put("data", "");
                    //返回客户
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                    return null;
                }
                //设置时间
                map.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                //设置设置人
                map.put("Creator", map.get("UserId"));
                //设置收藏字段
                map.put("isCollect", 0);
                result = workOrderListDao.setCollection(map);
            } else {
                //取消收藏
                if (null == existMap || existMap.size() == 0) {
                    obj.put("status", SMSEnum.type27.getIndex());
                    obj.put("msg", SMSEnum.type27.getName());
                    obj.put("data", "");
                    //返回客户
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                    return null;
                }
                map.put("DeleteTime", LocalTimeUtil.getRealCurrentTime());
                map.put("Deleter", map.get("UserId"));
                map.put("isCollect", -1);
                result = workOrderListDao.cancelCollection(map);
            }
            if (result > 0) {
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                obj.put("status", SMSEnum.type99.getIndex());
                obj.put("msg", SMSEnum.type99.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            //返回客户
            ParameterTool.writeErrorResponse(response);
            obj = null;
            return null;
        }
    }

    //时间轴
    @Override
    public ModelAndView workOrderFlowTime(Map<String, Object> map) {
        // TODO Auto-generated method stub
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String eAppVersion = MapUtils.getString(map,"eAppVersion");
        String dbuStatusCheck = appVersionTDao.getVersionCompatible("dbuStatusCheck");
        //因为需求变动   若新工单是通过服务经理改派后生成的工单   需要在时间轴中加入改派信息
        //根据新工单id获取所有的改派的旧工单信息
        //long newOrderId = Long.parseLong(map.get("OrderId").toString());
        //List<Map<String,Object>> oldWorkOrderList = workOrderListDao.getOldWorkOrderListByNewOrderId(newOrderId);
        //查询工单操作记录信息
        List<Map<String, Object>> list = workOrderListDao.getWorkOrderFlowTimeList(map);
        String resultJson = "";
        //如果工单状态不为空，获取列表信息
        //2.8.0   保存主副技师信息返给前端
        Map<String, Object> jsMsgMap = new HashMap<>();

        if (CollectionUtils.isNotEmpty(list)) {
            //返回数据
            List<Map<String, Object>> userlist = new ArrayList<>();
            Map<String, Object> mapss = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map1 = list.get(i);
                Map<String, Object> mapuser = new HashMap<>();
                mapuser.put("IsOverTime", MapUtils.getIntValue(map1, "IsOverTime"));
                String updateTime = MapUtils.getString(map1,"UpdateTime");
                Integer processStatus1 = MapUtils.getInteger(map1,"processStatus");
                Long orderId1 = MapUtils.getLong(map1,"OrderId");
                Map<String, Object> workOrderMap = workOrderTDao.getOrderById(orderId1);

                if (i == 0) {
                    mapss.put("stationName", map1.get("StationName"));
                    mapss.put("hotline", map1.get("HotlineTel"));
                    mapuser.put("CreateTime", workOrderMap.get("CreateTime"));
                } else {
                    mapuser.put("CreateTime", map1.get("CreateTime"));
                }

                if (MapUtils.getInteger(workOrderMap,"OrderChannel")==4&&(processStatus1==13||processStatus1==14)){
                    if (StringUtils.isNotEmpty(updateTime)) {
                        mapuser.put("CreateTime", updateTime);
                    }
                }
                if(processStatus1 == 40 && (StringUtils.isBlank(eAppVersion) || eAppVersion.compareTo(dbuStatusCheck) < 0)){
                   continue;
                }
                mapuser.put("processStatus", map1.get("processStatus"));
                mapuser.put("technicianName", map1.get("UserName"));
                mapuser.put("Phone", map1.get("Phone"));
                mapuser.put("comment", map1.get("ProcessComment"));
                if (map1.get("processStatus").toString().equals("6")) { //当工单状态为待派服务技师时
                    int isOutside = MapUtils.getInteger(map1, "IsOutside"); //1是外出   0是不外出
                    double guessDistance = MapUtils.getDouble(map1, "GuessDistance", 0D);
                    int isMoreThan = 0; //是否大于三百公里标志   1代表是   0代表否
                    if (isOutside == 1 && guessDistance >= 300) {
                        isMoreThan = 1;
                    }
                    mapuser.put("isMoreThan", isMoreThan);
                }

                if (map1.get("processStatus").toString().equals("7") || map1.get("processStatus").toString().equals("8")) {
                    //当工单状态为待服务技师接单时，把服务技师的姓名和手机号也返给前端
                    //考虑到网约技师没有待服务技师接单情况    增加8状态的判断
                    long orderid = MapUtils.getLongValue(map1, "OrderId", 0);
                    Map<String, Object> jsUser = userTDao.getUserByOrderId(orderid);
                    Map<String, Object> zjsMap = new HashMap<>();
                    if (MapUtils.isNotEmpty(jsUser)) {
                        mapuser.put("jsContact", jsUser.get("Contact"));
                        mapuser.put("jsPhone", jsUser.get("Phone"));
                        zjsMap.put("jsContact", jsUser.get("Contact"));
                        zjsMap.put("jsPhone", jsUser.get("Phone"));
                    }
                    jsMsgMap.put("zjsMsg", zjsMap);   //主技师信息

                    List<Map<String, Object>> fjsUserList = userTDao.getFuUserListByOrderId(orderid);
                    List<Map<String, Object>> fjsList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(fjsUserList)) {
                        for (Map<String, Object> fjsUser : fjsUserList) {
                            Map<String, Object> fjs = new HashMap<>();
                            fjs.put("jsContact", fjsUser.get("Contact"));
                            fjs.put("jsPhone", fjsUser.get("Phone"));
                            fjsList.add(fjs);
                        }
                    }
                    jsMsgMap.put("fjsMsg", fjsList);   //副技师信息
                }

                if (map1.get("processStatus").toString().equals("31")) { //当工单状态为异常关闭申请中时，通过操作人反查出角色，姓名，电话，返给前端
                    long creator = MapUtils.getLongValue(map1, "Creator");
                    Map<String, Object> roleNamesMap = rolesTDao.getRoleNamesByUserId(creator);
                    mapuser.put("roleNames", MapUtils.getString(roleNamesMap, "RoleNames"));
                    mapuser.put("creatorContact", MapUtils.getString(map1, "CreatorContact"));
                    mapuser.put("creatorPhone", MapUtils.getString(map1, "CreatorPhone"));
                }

                if (map1.get("processStatus").toString().equals("16")) { //当工单状态为异常关闭时，通过操作人反查出角色，姓名，电话，返给前端
                    long creator = MapUtils.getLongValue(map1, "Creator");
                    Map<String, Object> roleNamesMap = rolesTDao.getRoleNamesByUserId(creator);
                    mapuser.put("roleNames", MapUtils.getString(roleNamesMap, "RoleNames"));
                    mapuser.put("creatorContact", MapUtils.getString(map1, "CreatorContact"));
                    mapuser.put("creatorPhone", MapUtils.getString(map1, "CreatorPhone"));
                }

                // TODO 工单状态为：18/21时增加区域工程师的（姓名+电话）
                String processStatus = map1.get("processStatus").toString();
                if ("18".equals(processStatus) || "21".equals(processStatus)) {
                    // 根据服务工单id查询出服务工单对应的区域工程师
                    long orderId = MapUtils.getLongValue(map, "OrderId");
                    if (!Objects.isNull(orderId)) {
                        Map<String, Object> op = workOrderOperatorRelationDao.getOperatorByOrderId(orderId);
                        if (!Objects.isNull(op)) {
                            String name = MapUtils.getString(op, "Name");
                            String phone = MapUtils.getString(op, "Phone");
                            // 当区域工程师的姓名与手机号都不为空是返回
                            if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(phone)) {
                                mapuser.put("engName", name);
                                mapuser.put("engPhone", phone);
                            }
                        }
                    }
                }

                mapuser.put("RefuseReasonStation", MapUtils.getString(map1, "RefuseReasonStation", ""));
                mapuser.put("CloseReason", MapUtils.getString(map1, "CloseReason", ""));
                userlist.add(mapuser);
            }
            Map<String, Object> map4 = new HashMap<>();
            map4.put("stationInfo", mapss);
            map4.put("hisData", userlist);
            map4.put("jsMsg", jsMsgMap);
			/*if(CollectionUtils.isNotEmpty(oldWorkOrderList)){
				map4.put("oldWorkOrderList",oldWorkOrderList);
			}*/
            resultJson = ResultTemplate.successResult(SMSEnum.type0.getIndex(), SMSEnum.type0.getName(), map4);
        } else {
            resultJson = ResultTemplate.successResultNull();
        }
        ParameterTool.writeResponse(response, resultJson);
        return null;
    }

    /**
     * 客户工单列表
     */
    @Override
    public ModelAndView getCustomerOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //处理当前登录账户Id，获取账户手机号（用来后面关联工单使用）
            //String UserId = map.get("UserId").toString();
            UserT ut = UserThreadLocal.get();
            long lUserId = ut.getId();
            map.put("UserId", lUserId);
            String CustomerPhone = ut.getPhone();
            map.put("CustomerPhone", CustomerPhone);
            String eAppVersion = MapUtils.getString(map,"eAppVersion");
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//                page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0,1,2,3,4";
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                String dbuStatusCheck = appVersionTDao.getVersionCompatible("dbuStatusCheck");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    resultList = workOrderListDao.getNewCustomerOrderList(map);
                } else {
                    resultList = workOrderListDao.getCustomerOrderList(map);
                    //查询cds工单
                    getDRWorkOrderByOrderIdNew(resultList);
                }
                if (CollectionUtils.isNotEmpty(resultList)) {

                    for (WorkOrderInfo result : resultList) {
                        if (StringUtils.isEmpty(result.getRealESN())) {
                            result.setRealESN(result.getESN());
                        }
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        Integer[] statusAttr = new Integer[]{2,3,5,18,20,23,24,33};
                        List<Integer> statusList = Arrays.asList(statusAttr);
                        if(statusList.contains(orderStatusNo)){
                            orderStatusNo = 4;
                        } else if(orderStatusNo == 3){
                            if(result.getTransferReason().contains("用户不需要维修")){
                                orderStatusNo = 15;
                            } else {
                                orderStatusNo = 4;
                            }
                        } else if(orderStatusNo == 9){
                            orderStatusNo = 7;
                        } else if(orderStatusNo == 21){
                            orderStatusNo = 16;
                        } else if(orderStatusNo == 30){
                            orderStatusNo = 15;
                        } else if(orderStatusNo == 31){
                            if(result.getProcessStatus() != 0){
                                orderStatusNo = result.getProcessStatus();
                            }
                        } else if(orderStatusNo == 40 && (StringUtils.isBlank(eAppVersion) || eAppVersion.compareTo(dbuStatusCheck) < 0)){
                            orderStatusNo = 1;
                        }
                        for(DictionariesT dict : orderStatusList){
                            if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        if (result.getOrderSource() == 0 && result.getOrderStatusNo() == 25) { //工单来源是用户报单的并且状态为ccec400审核不通过的   工单状态显示待更新
                            result.setOrderStatus("待更新");
                        }
                    }
                }
                long et = System.currentTimeMillis() - st;
                log.info(String.format("终端用户工单列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 技师列表
     */
    @Override
    public ModelAndView getTechnicianOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        //获取ccec在企业表中主键id
        CompanyT ccecCompany = companyTDao.getCompanyInfoByCompanyNo("CCEC");
        map.put("ccecCompanyId", ccecCompany.getId());
        try {
            //处理当前登录账户Id，
            UserT ut = UserThreadLocal.get();
            long lUserId = ut.getId();
            map.put("UserId", lUserId);
            String CustomerPhone = ut.getPhone();
            map.put("CustomerPhone", CustomerPhone);
            long serviceStationId = ut.getServiceStationID();
            map.put("UserServiceStationId", serviceStationId);
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//                page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0,5,6";
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                /**
                 * 如果OrderId不为空时删除keyword
                 */
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    /**
                     * 如果keyword不为空时清除前后空格
                     */
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }

                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    resultList = workOrderListDao.getNewTechnicianOrderList(map);
                } else {
                    resultList = workOrderListDao.getTechnicianOrderList(map);
                    //查询cds工单
                    getDRWorkOrderByOrderIdNew(resultList);
                    if (CollectionUtils.isNotEmpty(resultList)) {
                        WorkOrderInfo result = resultList.get(0);
                        if (result.getOrderChannel()==1) {
                            if (result.getOrderSource()!=1) { //非站长报单
                                if (StringUtils.isBlank(result.getSellType()) ||"售前".equals(result.getSellType())|| "售时".equals(result.getSellType())) {
                                    // 售时，售后，售前  为空时  不可替换
                                    result.setOcrUpdateFlag(0);
                                }
                            }else {
                                if (StringUtils.isBlank(result.getAppVersion())||(StringUtils.isNotBlank(result.getAppVersion()) && result.getAppVersion().compareTo("3.28.0")<0)) {
                                    result.setOcrUpdateFlag(0);
                                }
                            }
                            // 添加是否是 道路非道路
                            if (StringUtils.isNotBlank(result.getMarketType())) {//道路
                                if ("Truck 卡车".equals(result.getMarketType())||"Bus 客车".equals(result.getMarketType())) {
                                    result.setEsnApplicationType(0);
                                }else {//非道路
                                    result.setEsnApplicationType(1);
                                }
                            }
                        }
                        if (result.getOrderChannel()==3) {
                            // 添加是否是 道路非道路
                            int esnApplicationType = 0;
                            //是否包含esn
                            if (StringUtils.isNotBlank(result.getESN())) {
                                EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(result.getESN());
                                if (null!=engineMasterData) {
                                    Map<String,Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
                                    if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(engineMasterData.getRelBulletinTelAboEmissionLevel()) && fleetEmissionLevelDicListMap.containsKey(engineMasterData.getRelBulletinTelAboEmissionLevel())){
                                        Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,engineMasterData.getRelBulletinTelAboEmissionLevel());
                                        if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                                            esnApplicationType = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                                        }
                                    }
                                    result.setEsnApplicationType(esnApplicationType);
                                }
                            }
                            //amt工单默认为 道路
                            if(StringUtils.isNotBlank(result.getAmtNo())){
                                result.setEsnApplicationType(0);
                            }
                            //默认可编辑
                            result.setOcrUpdateFlag(1);
                        }
                        if (result.getOrderChannel()==4) {
                            //xcec 默认为道路
                            result.setEsnApplicationType(0);
                            //默认可编辑
                            result.setOcrUpdateFlag(1);
                        }
                        //获取ocr的地址
                        String emailReminderChannel = dictionariesTDao.getListByDTableName(OCRURL);
                        if (StringUtils.isNotBlank(emailReminderChannel)) {
                            List<String> emailReminderChannelList = JSON.parseArray(emailReminderChannel, String.class);
                            result.setOcrUrl(emailReminderChannelList.get(1));// 地址
                            result.setFileType(emailReminderChannelList.get(0));//0 代表  appservice,1 代表其他的服务器
                        }
                        WorkOrderInfo diagnose = diagnoseConclusionTDao.getDiagnoseByOrderId(result.getOrderId());
                        if(null != diagnose){
                            result.setFaultSolution(diagnose.getFaultSolution());
                            result.setInvalidModel(diagnose.getInvalidModel());
                            result.setProblemLevel(diagnose.getProblemLevel());
                        }
                        List<Integer> orderStatus = techDealWithWorkOrderDao.getOrderStatusOrderId(result.getOrderId());
                        if(CollectionUtils.isNotEmpty(orderStatus)){
                            if(orderStatus.contains(10) && !orderStatus.contains(11)){
                                result.setFuStatus(1);
                            } else if(orderStatus.contains(11)){
                                result.setFuStatus(2);
                            }
                        }

                        //新增判断是否满足维修确认条件和是否完成维修确认
                        Map<String, Object> workOrderDR = workOrderTDao.getDRWorkOrderByOrderId(MapUtils.getLong(map, "OrderId"));
                        if(null != workOrderDR && MapUtils.getInteger(workOrderDR, "IsOpenRepairAck",0) == 1){
                            result.setIsFinishRepairAck(MapUtils.getInteger(workOrderDR, "IsFinishRepairAck",0));
                            //根据诊断工单id 查询是否满足维修确认条件
                            int count = workOrderDrDao.isFitRepairAck(MapUtils.getLong(workOrderDR, "ID"));
                            log.info(String.format("有零件的数量：", count));
                            if(count > 0){
                                result.setIsFitRepairAck(1);
                            }
                        }
                    }

                }

                if (CollectionUtils.isNotEmpty(resultList)) {
                    List<Long> orderIdList = resultList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //获取用户姓名
                    List<WorkOrderInfo> qyEngineerNameList = workOrderOperatorRelationDao.getOperatorByOrderIdList(orderIdList);
                    //获取工单收藏
                    List<WorkOrderInfo> favorateList = workOrderListDao.getFavorateByOrderIdList(orderIdList,lUserId);
                    for (WorkOrderInfo result : resultList) {
                        if (StringUtils.isEmpty(result.getRealESN())) {
                            result.setRealESN(result.getESN());
                        }
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        if(orderStatusNo == 30){
                            orderStatusNo = 15;
                        }
                        for(DictionariesT dict : orderStatusList){
                            if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        if(result.getOrderChannel() == 4 && result.getIsTechSupport() == 1 && orderStatusNo ==  2){
                            result.setOrderStatus("待大区经理确认");
                        }
                        //获取用户姓名
                        for(WorkOrderInfo qyEngineerName : qyEngineerNameList){
                            if(result.getOrderId().equals(qyEngineerName.getOrderId())){
                                result.setQyEngineerName(qyEngineerName.getQyEngineerName());
                            }
                        }
                        //获取工单收藏
                        for(WorkOrderInfo favorate : favorateList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setIsCollect(1);
                            }
                        }
                    }
                }

                handleFieldsNew(resultList);


                /**
                 *  添加时间 2021-04-27
                 *  3.1.0需求服务技师 XCEC-工单列表、详情页面增加处理时长字段
                 */
                try {
                    addHandleTimeForTechNew(resultList);
                } catch (Exception e) {
                    log.error("XCEC服务工单添加处理时长字段失败", e);
                }


                // 拼装是否需要补拍逻辑
                getRemedyInfoNew(MapUtils.getString(map, "OrderId"), resultList);
                //返回数据
                long et = System.currentTimeMillis() - st;
                log.info(String.format("技师工单列表响应消耗时间: %d", et));
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            // TODO: handle exception
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }


    /**
     * 服务商站长工单列表
     */
    @Override
    public ModelAndView getStationmasterOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //处理当前登录账户Id，
            UserT ut = UserThreadLocal.get();
            long lUserId = ut.getId();
            map.put("UserId", lUserId);
            long ServiceStationId = ut.getServiceStationID();
            map.put("ServiceStationId", ServiceStationId);
            String eAppVersion = MapUtils.getString(map,"eAppVersion");
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//                page = (int) Double.parseDouble(map.get("page").toString());
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0,1,3,4,7,14,15,16";   //3.2.0  站长增加待400审核，待400回访，异常关闭功能项
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }

                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                String dbuStatusCheck = appVersionTDao.getVersionCompatible("dbuStatusCheck");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                // 解决app端    质量索赔不为空时，不弹框的问题+++++++++开始
                boolean isOrderDetailFlag = false;
                // 解决app端    质量索赔不为空时，不弹框的问题+++++++++结束
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    resultList = workOrderListDao.getNewStationmasterOrderListIsCreat(map);
                } else {
                    // 解决app端    质量索赔不为空时，不弹框的问题+++++++++开始
                    isOrderDetailFlag = true;
                    // 解决app端    质量索赔不为空时，不弹框的问题+++++++++结束
                    resultList = workOrderListDao.getStationmasterOrderList(map);
                    //查询cds工单
                    getDRWorkOrderByOrderIdNew(resultList);
                    if (CollectionUtils.isNotEmpty(resultList)) {
                        WorkOrderInfo result = resultList.get(0);
                        WorkOrderInfo diagnose = diagnoseConclusionTDao.getDiagnoseByOrderId(result.getOrderId());
                        if (null != diagnose) {
                            result.setFaultSolution(diagnose.getFaultSolution());
                            result.setInvalidModel(diagnose.getInvalidModel());
                            result.setProblemLevel(diagnose.getProblemLevel());
                        }
                    }
                }

                handleFieldsNew(resultList);


                // 拼装是否需要补拍逻辑
                getRemedyInfoNew(MapUtils.getString(map, "OrderId"), resultList);
                if (CollectionUtils.isNotEmpty(resultList)) {
                    List<Long> orderIdList = resultList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //获取工单收藏
                    List<WorkOrderInfo> favorateList = workOrderListDao.getFavorateByOrderIdList(orderIdList,lUserId);
                    //获取主动升级工单
                    List<WorkOrderInfo> escalationList = escalationOrderTDao.getEscalationByOrderIdList(orderIdList);
                    //服务站关系类型
                    List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);
                    for (WorkOrderInfo result : resultList) {
                        if (StringUtils.isEmpty(result.getRealESN())) {
                            result.setRealESN(result.getESN());
                        }
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        if(orderStatusNo == 30){
                            orderStatusNo = 15;
                        } else if(orderStatusNo == 40 && (StringUtils.isBlank(eAppVersion) || eAppVersion.compareTo(dbuStatusCheck) < 0)){
                            orderStatusNo = 1;
                        }
                        for(DictionariesT dict : orderStatusList){
                            if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        if(result.getOrderChannel() == 4 && result.getIsTechSupport() == 1 && orderStatusNo ==  2){
                            result.setOrderStatus("待大区经理确认");
                        }
                        if (result.getOrderSource() == 1 && result.getOrderStatusNo() == 25) { //工单来源是用户报单的并且状态为ccec400审核不通过的   工单状态显示待更新
                            result.setOrderStatus("待更新");
                        }
                        //获取工单收藏
                        for(WorkOrderInfo favorate : favorateList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setIsCollect(1);
                            }
                        }
                        //获取主动升级工单
                        for(WorkOrderInfo favorate : escalationList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setEscalationOrderID(favorate.getId());
                            }
                        }
                        //服务站关系类型
                        boolean isPrin = false;
                        for(Long orderId : principalList){
                            if(result.getOrderId().equals(orderId)){
                                isPrin = true;
                            }
                        }
                        if(isPrin){
                            if(!result.getStationRelationType().equals(2)){
                                result.setStationRelationType(1);
                            }
                        } else {
                            result.setStationRelationType(0);
                        }
                        // 服务站拒单后区域服务经理改派后，旧工单看到的还是“服务商已拒单”拒单状态
                        if (result.getOrderStatusNo() == 3) {
                            List<Integer> statusList = workOrderListDao.getprocessStatusByOrderId(result.getOrderId());
                            if (statusList != null && statusList.size() > 0) {
                                if (statusList.contains(3) && (statusList.contains(5))) {
                                    result.setOrderStatus("服务商已拒单");
                                    result.setOrderStatusNo(5);
                                }
                            }
                        }
                        // 解决app端    质量索赔不为空时，不弹框的问题+++++++++开始
                        if (isOrderDetailFlag) {
                            int orderSource = result.getOrderSource();
                            String OrderStatus = result.getOrderStatus();
                            String NatureClaim = result.getNatureClaim();
                            int OrderChannel = result.getOrderChannel();
                            if ((orderSource == 0 || orderSource == 2) && "待服务商接单".equals(OrderStatus) && StringUtils.isNotBlank(NatureClaim) && NatureClaim.equals("1") && OrderChannel == 3) {
                                result.setNatureClaim(null);
                            }
                        }
                        // 解决app端    质量索赔不为空时，不弹框的问题+++++++++结束
                    }
                }
                long et = System.currentTimeMillis() - st;
                log.info(String.format("站长工单列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            // TODO: handle exception
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }

    /**
     * @description: 根据工单id查询时间轴
     * @param:
     * @return:
     * @exception:
     * @author: shiliqiang
     * @company: CTY Technology Co.,Ltd
     * @since: 2021/8/2 18:14
     * @version: V1.0
     */
    private List<Integer> getPerationData(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        map.put("OrderId", orderId);
        //查询工单操作记录信息
        List<Map<String, Object>> list = workOrderListDao.getWorkOrderFlowTimeList(map);
        List<Integer> statusList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map1 = list.get(i);
                Integer orderStatus = (Integer)map1.get("processStatus");
                statusList.add(orderStatus);
            }
            return statusList;
        }
        return statusList;
    }

    private void handleFields(List<Map<String, Object>> resultList) {
        /**
         * 3.1.0 修改了服务子类型的名称
         * 为了兼容旧的数据，在返回的详情字段中，会把旧的服务子类型名称转换成新的名称 (⊙﹏⊙)b
         */
        if (CollectionUtils.isNotEmpty(resultList)) {
            resultList.forEach(map -> {
                String serviceSubType = MapUtils.getString(map, "ServiceSubtype", "");
                if (StringUtils.isNotEmpty(serviceSubType)) {
                    serviceSubType = Arrays.stream(serviceSubType.split(";")).map(e -> {
                        switch (e) {
                            case "首保":
                                return "首次保养";
                            case "保养":
                                return "保养记录";
                            case "BIS服务":
                                return "厂内服务";
                            case "统修":
                                return "统修整改";
                            case "故障维修":
                                return "故障处理";
                            default:
                                return e;
                        }
                    }).collect(Collectors.joining(";"));
                }
                map.put("ServiceSubtype", serviceSubType);
                map.put("UnifiedRepairNo", MapUtils.getString(map, "UnifiedRepairNo", ""));
            });
        }
    }

    private void handleFieldsNew(List<WorkOrderInfo> resultList) {
        /**
         * 3.1.0 修改了服务子类型的名称
         * 为了兼容旧的数据，在返回的详情字段中，会把旧的服务子类型名称转换成新的名称 (⊙﹏⊙)b
         */
        if (CollectionUtils.isNotEmpty(resultList)) {
            resultList.forEach(info -> {
                String serviceSubType =info.getServiceSubtype();
                if (StringUtils.isNotEmpty(serviceSubType)) {
                    serviceSubType = Arrays.stream(serviceSubType.split(";")).map(e -> {
                        switch (e) {
                            case "首保":
                                return "首次保养";
                            case "保养":
                                return "保养记录";
                            case "BIS服务":
                                return "厂内服务";
                            case "统修":
                                return "统修整改";
                            case "故障维修":
                                return "故障处理";
                            default:
                                return e;
                        }
                    }).collect(Collectors.joining(";"));
                }
                info.setServiceSubtype(serviceSubType);
            });
        }
    }

    /**
     * 工单的处理阶段
     * 分为三个阶段
     * 技师维修完成阶段
     * 工单异常关闭阶段
     * 工单处理中阶段
     */
    private enum WorkOrderHandlePhase {
        SERVICE_FINISHIED("技师维修完成"),

        HANDLING("工单处理中"),

        CLOSE("关闭状态");

        private String desc;

        WorkOrderHandlePhase(String desc) {
            this.desc = desc;
        }

        @SuppressWarnings("unused")
        public String getDesc() {
            return this.desc;
        }
    }


    /**
     * 添加时间 2021-04-27
     * 3.1.0需求服务技师工单列表、详情页面增加处理时长字段
     * 参数说明：
     * 服务工单列表
     */
    public void addHandleTimeForTech(List<Map<String, Object>> orderList) {
        /**
         * 处理时长分类三种情况：
         * 		第一种：服务工单被异常关闭  此时：处理时长 ＝ 异常关闭的时间 － 工单创建时间
         * 		第二种：服务工单被服务完成  此时：处理时长 ＝ 用户待评价／服务完成时间  － 工单创建时间
         * 		第三种：服务工单状态并未进入异常关闭状态或用户待评价、服务完成状态
         * 									此时：处理时长 ＝ 当前系统时间 － 工单创建时间
         *
         * 					|-----------------用户待评价／服务完成时间
         * 服务工单---------|
         * 					|-----------------异常关闭
         *
         */
        if (CollectionUtils.isNotEmpty(orderList)) {
            /**
             * 第一步 先过滤出各个阶段的服务工单
             * 注意：只包含XCEC渠道的服务工单
             */
            Map<WorkOrderHandlePhase, Map<Long, Map<String, Object>>> orderPhaseMap = new HashMap<>();
            for (Map<String, Object> order : orderList) {
                // 获取当前工单的状态
                int orderStatus = MapUtils.getIntValue(order, "OrderStatusNo");

                WorkOrderHandlePhase handlePhase = null;

                switch (orderStatus) {
                    // 订单处于异常关闭状态
                    case 16:
                        handlePhase = WorkOrderHandlePhase.CLOSE;
                        break;
                    // 订单处于用户待评价 或 服务完成时间
                    case 13:
                    case 14:
                        handlePhase = WorkOrderHandlePhase.SERVICE_FINISHIED;
                        break;
                    // 订单处于处理中
                    default:
                        handlePhase = WorkOrderHandlePhase.HANDLING;
                }
                // 对服务工单进行分组
                workOrderGroupBy(orderPhaseMap, handlePhase, order);
            }
            /**
             *  第二步 分别设置每个阶段服务工单的处理时长
             */
            // 设置异常关闭的服务工单处理时长
            setDealTimeByExceptionCloseTime(orderPhaseMap.get(WorkOrderHandlePhase.CLOSE));

            // 设置技师服务完成的处理时长
            setDealTimeByServiceFinishedTime(orderPhaseMap.get(WorkOrderHandlePhase.SERVICE_FINISHIED));

            // 设置工单处于进行中的处理时长
            setDealTimeByHandlingTime(orderPhaseMap.get(WorkOrderHandlePhase.HANDLING));

        }

    }


    /**
     * 添加时间 2021-04-27
     * 3.1.0需求服务技师工单列表、详情页面增加处理时长字段
     * 参数说明：
     * 服务工单列表
     */
    public void addHandleTimeForTechNew(List<WorkOrderInfo> orderList) {
        /**
         * 处理时长分类三种情况：
         * 		第一种：服务工单被异常关闭  此时：处理时长 ＝ 异常关闭的时间 － 工单创建时间
         * 		第二种：服务工单被服务完成  此时：处理时长 ＝ 用户待评价／服务完成时间  － 工单创建时间
         * 		第三种：服务工单状态并未进入异常关闭状态或用户待评价、服务完成状态
         * 									此时：处理时长 ＝ 当前系统时间 － 工单创建时间
         *
         * 					|-----------------用户待评价／服务完成时间
         * 服务工单---------|
         * 					|-----------------异常关闭
         *
         */
        if (CollectionUtils.isNotEmpty(orderList)) {
            /**
             * 第一步 先过滤出各个阶段的服务工单
             * 注意：只包含XCEC渠道的服务工单
             */
            Map<WorkOrderHandlePhase, Map<Long, WorkOrderInfo>> orderPhaseMap = new HashMap<>();
            for (WorkOrderInfo order : orderList) {
                // 获取当前工单的状态
                int orderStatus = order.getOrderStatusNo();

                WorkOrderHandlePhase handlePhase = null;

                switch (orderStatus) {
                    // 订单处于异常关闭状态
                    case 16:
                        handlePhase = WorkOrderHandlePhase.CLOSE;
                        break;
                    // 订单处于用户待评价 或 服务完成时间
                    case 13:
                    case 14:
                        handlePhase = WorkOrderHandlePhase.SERVICE_FINISHIED;
                        break;
                    // 订单处于处理中
                    default:
                        handlePhase = WorkOrderHandlePhase.HANDLING;
                }
                // 对服务工单进行分组
                workOrderGroupByNew(orderPhaseMap, handlePhase, order);
            }
            /**
             *  第二步 分别设置每个阶段服务工单的处理时长
             */
            // 设置异常关闭的服务工单处理时长
            setDealTimeByExceptionCloseTimeNew(orderPhaseMap.get(WorkOrderHandlePhase.CLOSE));

            // 设置技师服务完成的处理时长
            setDealTimeByServiceFinishedTimeNew(orderPhaseMap.get(WorkOrderHandlePhase.SERVICE_FINISHIED));

            // 设置工单处于进行中的处理时长
            setDealTimeByHandlingTimeNew(orderPhaseMap.get(WorkOrderHandlePhase.HANDLING));

        }

    }

    /**
     * 根据异常关闭时间设置处理时长
     * 参数说明：
     * key=OrderId  value=WorkOrder
     * 处理时长 = 服务工单异常关闭时间 - 工单创建时间
     */
    private void setDealTimeByExceptionCloseTime(Map<Long, Map<String, Object>> closeMap) {
        if (MapUtils.isNotEmpty(closeMap)) {

            // 查询出这些服务工单的异常关闭时间
            Map<Long, Map<String, Object>> closeOrderMap = workOrderListDao.getExceptionCloseTimeByOrderIds(new ArrayList<>(closeMap.keySet()));

            // 设置异常关闭的服务工单的处理时长
            for (Entry<Long, Map<String, Object>> kv : closeMap.entrySet()) {
                // 服务工单id
                Long orderId = kv.getKey();
                // 服务工单
                Map<String, Object> orderMap = kv.getValue();

                if (MapUtils.isNotEmpty(closeOrderMap) && closeOrderMap.containsKey(orderId)) {

                    // 获取当前服务工单的异常关闭时间
                    String exCloseTime = MapUtils.getString(closeOrderMap.get(orderId), "CloseTime");
                    // 服务工单创建时间
                    String orderCreateTime = MapUtils.getString(orderMap, "CreateTime");

                    // 处理时长 = 工单异常关闭时间 - 工单的创建时间
                    long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, exCloseTime);
                    orderMap.put("DealTime", seconds);
                    continue;
                }
                orderMap.put("DealTime", 0);
                log.info(String.format("未找到服务工单ID为:%s的异常关闭时间", orderId));

            }
        }
    }

    /**
     * 设置服务工单为技师维修完成的处理时长
     * 参数说明：
     * key=OrderId		value=WorkOrder
     * 解释：服务工单为技师维修完成(包含待用户评价和服务完成2种状态)
     * 处理时长分为2种：
     * 第一种：工单包含待用户评价状态  此时：处理时长 = 工单进入待用户评价的时间 - 工单创建时间
     * 第二种：有些用户不存在e路app系统，此时技师维修完成后，工单直接进入服务完成状态  此时：处理时长 = 工单进入服务完成状态时间 - 工单创建时间
     */
    private void setDealTimeByServiceFinishedTime(Map<Long, Map<String, Object>> finishedMap) {

        if (MapUtils.isNotEmpty(finishedMap)) {
            // 获取服务工单技师维修完成的时间
            // Map包含的属性：OrderId  ProcessStatus  FinishedTime
            List<Map<String, Object>> repairFinishedTimeList = workOrderListDao.getRepairFinishedTimeByOrderIds(new ArrayList<>(finishedMap.keySet()));


            // 设置服务工单的处理时长
            for (Entry<Long, Map<String, Object>> kv : finishedMap.entrySet()) {
                // 服务工单id
                Long orderId = kv.getKey();
                // 服务工单
                Map<String, Object> orderMap = kv.getValue();

                if (CollectionUtils.isNotEmpty(repairFinishedTimeList)) {
                    // 对repairFinishedTimeList进行按OrderId分组
                    Map<Long, List<Map<String, Object>>> byResult = repairFinishedTimeList.stream().collect(Collectors.groupingBy(ft -> MapUtils.getLong(ft, "OrderId")));

                    if (byResult.containsKey(orderId)) {
                        // 当前工单对应的维修完成时间(只包含工单状态13、14的流水) 注：可能只包含13、14其它的一个，最多包含2个
                        List<Map<String, Object>> ftList = byResult.get(orderId);

                        // 如果ftList的size=1说明当前工单只有状态为13或14的流水   注：因为有些工单压根没有13这个状态
                        if (ftList.size() > 1) {
                            // 从ftList中取出工单状态为13的工单维修完成时间  ftList的size大于1时，一定会包含状态为13的工单维修时间，且只有一个；
                            ftList = ftList.stream().filter(ft -> MapUtils.getIntValue(ft, "ProcessStatus") == 13).collect(Collectors.toList());
                        }

                        computeDealTime(ftList, orderMap);
                        continue;
                    }
                }

                // 如果没有找到默认设置处理时长为0
                orderMap.put("DealTime", 0);
                log.info(String.format("未找到服务工单ID为：%d的维修完成时间", orderId));
            }

        }
    }


    /**
     * 计算处理时长
     */
    private void computeDealTime(List<Map<String, Object>> orderTimeList, Map<String, Object> orderMap) {
        Map<String, Object> ft = orderTimeList.get(0);
        // 工单的技师维修完成时间
        String finishedTime = MapUtils.getString(ft, "FinishedTime");
        // 工单创建时间
        String orderCreateTime = MapUtils.getString(orderMap, "CreateTime");
        // 计算出处理时长 单位：秒
        long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, finishedTime);
        orderMap.put("DealTime", seconds);
    }


    /**
     * 设置服务工单为进行中处理时长
     * 参数说明：
     * key=OrderId  value=WorkOrder
     * 解释：服务工单为进行中的处理时长 = 当前系统时间 - 工单创建时间
     */
    private void setDealTimeByHandlingTime(Map<Long, Map<String, Object>> handlingMap) {

        if (MapUtils.isNotEmpty(handlingMap)) {

            handlingMap.values().forEach(wo -> {

                // 当前系统时间
                String currentTime = LocalTimeUtil.getRealCurrentTime();
                // 服务工单的创建时间
                String orderCreateTime = MapUtils.getString(wo, "CreateTime");
                // 工单异常关闭时间 - 工单的创建时间
                long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, currentTime);
                wo.put("DealTime", seconds);

            });
        }
    }


    /**
     * 服务工单进行分组
     * 分为三组：
     * 一组：技师维修完成
     * 二组：服务工单异常关闭
     * 三组：服务工单处理中
     */
    private void workOrderGroupBy(Map<WorkOrderHandlePhase, Map<Long, Map<String, Object>>> orderPhaseMap, WorkOrderHandlePhase key, Map<String, Object> order) {

        // 如果当前服务工单不是XCEC渠道的不添加到分组
        int orderChannel = MapUtils.getIntValue(order, "OrderChannel");
        if (orderChannel != 4) {
            return;
        }

        Map<Long, Map<String, Object>> subMap = orderPhaseMap.get(key);

        if (null == subMap) {
            subMap = new HashMap<>();
            orderPhaseMap.put(key, subMap);
        }
        // 服务工单ID
        Long orderId = MapUtils.getLong(order, "OrderId");
        subMap.put(orderId, order);
    }


    /**
     * 服务工单进行分组
     * 分为三组：
     * 一组：技师维修完成
     * 二组：服务工单异常关闭
     * 三组：服务工单处理中
     */
    private void workOrderGroupByNew(Map<WorkOrderHandlePhase, Map<Long, WorkOrderInfo>> orderPhaseMap, WorkOrderHandlePhase key, WorkOrderInfo order) {

        // 如果当前服务工单不是XCEC渠道的不添加到分组
        int orderChannel = order.getOrderChannel();
        if (orderChannel != 4) {
            return;
        }

        Map<Long, WorkOrderInfo> subMap = orderPhaseMap.get(key);

        if (null == subMap) {
            subMap = new HashMap<>();
            orderPhaseMap.put(key, subMap);
        }
        // 服务工单ID
        Long orderId = order.getOrderId();
        subMap.put(orderId, order);
    }

    /**
     * 根据异常关闭时间设置处理时长
     * 参数说明：
     * key=OrderId  value=WorkOrder
     * 处理时长 = 服务工单异常关闭时间 - 工单创建时间
     */
    private void setDealTimeByExceptionCloseTimeNew(Map<Long, WorkOrderInfo> closeMap) {
        if (MapUtils.isNotEmpty(closeMap)) {

            // 查询出这些服务工单的异常关闭时间
            Map<Long, Map<String, Object>> closeOrderMap = workOrderListDao.getExceptionCloseTimeByOrderIds(new ArrayList<>(closeMap.keySet()));

            // 设置异常关闭的服务工单的处理时长
            for (Entry<Long, WorkOrderInfo> kv : closeMap.entrySet()) {
                // 服务工单id
                Long orderId = kv.getKey();
                // 服务工单
                WorkOrderInfo orderMap = kv.getValue();

                if (MapUtils.isNotEmpty(closeOrderMap) && closeOrderMap.containsKey(orderId)) {

                    // 获取当前服务工单的异常关闭时间
                    String exCloseTime = MapUtils.getString(closeOrderMap.get(orderId), "CloseTime");
                    // 服务工单创建时间
                    String orderCreateTime = orderMap.getCreateTime();

                    // 处理时长 = 工单异常关闭时间 - 工单的创建时间
                    long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, exCloseTime);
                    orderMap.setDealTime(seconds);
                    continue;
                }
                log.info(String.format("未找到服务工单ID为:%s的异常关闭时间", orderId));
            }
        }
    }

    /**
     * 设置服务工单为技师维修完成的处理时长
     * 参数说明：
     * key=OrderId		value=WorkOrder
     * 解释：服务工单为技师维修完成(包含待用户评价和服务完成2种状态)
     * 处理时长分为2种：
     * 第一种：工单包含待用户评价状态  此时：处理时长 = 工单进入待用户评价的时间 - 工单创建时间
     * 第二种：有些用户不存在e路app系统，此时技师维修完成后，工单直接进入服务完成状态  此时：处理时长 = 工单进入服务完成状态时间 - 工单创建时间
     */
    private void setDealTimeByServiceFinishedTimeNew(Map<Long, WorkOrderInfo> finishedMap) {

        if (MapUtils.isNotEmpty(finishedMap)) {
            // 获取服务工单技师维修完成的时间
            // Map包含的属性：OrderId  ProcessStatus  FinishedTime
            List<Map<String, Object>> repairFinishedTimeList = workOrderListDao.getRepairFinishedTimeByOrderIds(new ArrayList<>(finishedMap.keySet()));


            // 设置服务工单的处理时长
            for (Entry<Long,WorkOrderInfo> kv : finishedMap.entrySet()) {
                // 服务工单id
                Long orderId = kv.getKey();
                // 服务工单
                WorkOrderInfo orderMap = kv.getValue();

                if (CollectionUtils.isNotEmpty(repairFinishedTimeList)) {
                    // 对repairFinishedTimeList进行按OrderId分组
                    Map<Long, List<Map<String, Object>>> byResult = repairFinishedTimeList.stream().collect(Collectors.groupingBy(ft -> MapUtils.getLong(ft, "OrderId")));

                    if (byResult.containsKey(orderId)) {
                        // 当前工单对应的维修完成时间(只包含工单状态13、14的流水) 注：可能只包含13、14其它的一个，最多包含2个
                        List<Map<String, Object>> ftList = byResult.get(orderId);

                        // 如果ftList的size=1说明当前工单只有状态为13或14的流水   注：因为有些工单压根没有13这个状态
                        if (ftList.size() > 1) {
                            // 从ftList中取出工单状态为13的工单维修完成时间  ftList的size大于1时，一定会包含状态为13的工单维修时间，且只有一个；
                            ftList = ftList.stream().filter(ft -> MapUtils.getIntValue(ft, "ProcessStatus") == 13).collect(Collectors.toList());
                        }

                        computeDealTimeNew(ftList, orderMap);
                        continue;
                    }
                }

                // 如果没有找到默认设置处理时长为0
                orderMap.setDealTime(0L);
                log.info(String.format("未找到服务工单ID为：%d的维修完成时间", orderId));
            }

        }
    }


    /**
     * 计算处理时长
     */
    private void computeDealTimeNew(List<Map<String, Object>> orderTimeList, WorkOrderInfo orderMap) {
        Map<String, Object> ft = orderTimeList.get(0);
        // 工单的技师维修完成时间
        String finishedTime = MapUtils.getString(ft, "FinishedTime");
        // 工单创建时间
        String orderCreateTime = orderMap.getCreateTime();
        // 计算出处理时长 单位：秒
        long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, finishedTime);
        orderMap.setDealTime(seconds);
    }


    /**
     * 设置服务工单为进行中处理时长
     * 参数说明：
     * key=OrderId  value=WorkOrder
     * 解释：服务工单为进行中的处理时长 = 当前系统时间 - 工单创建时间
     */
    private void setDealTimeByHandlingTimeNew(Map<Long, WorkOrderInfo> handlingMap) {

        if (MapUtils.isNotEmpty(handlingMap)) {

            handlingMap.values().forEach(wo -> {

                // 当前系统时间
                String currentTime = LocalTimeUtil.getRealCurrentTime();
                // 服务工单的创建时间
                String orderCreateTime = wo.getCreateTime();
                // 工单异常关闭时间 - 工单的创建时间
                long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, currentTime);
                wo.setDealTime(seconds);

            });
        }
    }
    /**
     * dcec和xcec服务经理   ccec 400工单列表
     */
    @Override
    public ModelAndView getManagerOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            UserT ut = UserThreadLocal.get();
            long companyId = ut.getCompanyId();
            map.put("companyId", companyId);
            long lUserId = ut.getId();
            map.put("UserId", lUserId);
            String Phone = ut.getPhone();
            map.put("Phone", Phone);
            map.put("UserPhone", Phone);
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//				page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            //获取ccec在企业表中主键id
            CompanyT ccecCompany = companyTDao.getCompanyInfoByCompanyNo("CCEC");
            map.put("ccecCompanyId", ccecCompany.getId());
            String OrderTypeStr = "0,8,9,12,14,15,16";    //2.8.0ccec400增加14,15,16
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }
                //首先查询该区域服务经理手下有几个服务站（服务站ID是啥）
                map.put("Level", 1);//level=1 表示区域服务经理
                List<Map<String, Object>> stationList = workOrderListDao.getManagerHasStations(map);
                if(CollectionUtils.isNotEmpty(stationList)){
                    List<Long> stationIds = new ArrayList<>();
                    for (Map<String, Object> mmap : stationList) {
                        stationIds.add(MapUtils.getLong(mmap,"serviceStationId"));
                    }
                    if (companyId == ccecCompany.getId()) { //ccec渠道的400获取工单
                        stationIds.add(0L);
                    }
                    map.put("stationIds", stationIds);
                } else {
                    JSONObject jb = new JSONObject();
                    obj.put("status", -16);
                    obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-16));
                    obj.put("data", jb);
                    //返回客户
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                    return null;
                }
                //获取当前系统时间
                map.put("nowTime", LocalTimeUtil.getRealCurrentTime());
                //当前时间前24小时
                map.put("twentyTime", LocalTimeUtil.minusHoursToTime(24));
                //当前时间前8小时
                map.put("eightTime", LocalTimeUtil.minusHoursToTime(8));
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    resultList = workOrderListDao.getNewManagerOrderList(map);
                } else {
                    resultList = workOrderListDao.getManagerOrderList(map);
                    if(CollectionUtils.isNotEmpty(resultList)){
                        WorkOrderInfo result = resultList.get(0);
                        //当前时间，只要年月日
                        String currentTime = LocalTimeUtil.getRealCurrentDate();
                        int ccecPassByEsnCount = workOrderTDao.getCCECPassCountByEsn(result.getESN(),currentTime);
                        //sprint37需求    CDAP-1888    校验当前esn当天是否存在ccec400指派过的工单
                        //ESNHasDesignatedToday 这个字段  0 是未指派过，1是指派过
                        if(ccecPassByEsnCount > 0){
                            result.setESNHasDesignatedToday(1);
                        }
                        //2.10.0回访工单详情页面，通过工单流转表查询维修完成的时间点，并赋值给ConfirmModifyTime供前台展示
                        Map<String, Object> workOrderFlowMap = workOrderFlowTDao.getWorkOrderFlowByOrderIdAndStatus(MapUtils.getLong(map,"OrderId"), 13);
                        result.setConfirmModifyTime(MapUtils.getString(workOrderFlowMap,"CreateTime"));
                    }
                }
                //循环处理查询列表（审核不通过、已取消、异常关闭、待用户评价
                // 待用户评价-400远程解决 28  400已关闭29   取消中30    异常关闭申请中31
                // 这几种情况下，处理时长=这几种动作发生时间-工单生成时间）
                if (CollectionUtils.isNotEmpty(resultList)) {
                    List<Long> orderIdList = resultList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //获取工单收藏
                    List<WorkOrderInfo> favorateList = workOrderListDao.getFavorateByOrderIdList(orderIdList, lUserId);
                    //服务站关系类型
                    List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);

                    for (WorkOrderInfo result : resultList) {
                        if (StringUtils.isEmpty(result.getRealESN())) {
                            result.setRealESN(result.getESN());
                        }
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        if (orderStatusNo == 30) {
                            orderStatusNo = 15;
                        }
                        for (DictionariesT dict : orderStatusList) {
                            if (dict.getDInt().equals(String.valueOf(orderStatusNo))) {
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        if(result.getOrderChannel() == 4 && result.getIsTechSupport() == 1 && orderStatusNo ==  2){
                            result.setOrderStatus("待大区经理确认");
                        }
                        //获取工单收藏
                        for (WorkOrderInfo favorate : favorateList) {
                            if (result.getOrderId().equals(favorate.getOrderId())) {
                                result.setIsCollect(1);
                            }
                        }
                        //服务站关系类型
                        boolean isPrin = false;
                        for (Long orderId : principalList) {
                            if (result.getOrderId().equals(orderId)) {
                                isPrin = true;
                            }
                        }
                        if (isPrin) {
                            if (!result.getStationRelationType().equals(2)) {
                                result.setStationRelationType(1);
                            }
                        } else {
                            result.setStationRelationType(0);
                        }

                        Integer OrderStatus = result.getOrderStatusNo();

                        if (null != OrderStatus) {
                            //审核不通过
                            if (OrderStatus.equals(3) || OrderStatus.equals(15)
                                    || OrderStatus.equals(13) || OrderStatus.equals(16)
                                    || OrderStatus.equals(5) || OrderStatus.equals(14)
                                    || OrderStatus.equals(28) || OrderStatus.equals(29)
                                    || OrderStatus.equals(30)
                                    || OrderStatus.equals(31)
                                    || OrderStatus.equals(20) || OrderStatus.equals(21)
                                    || OrderStatus.equals(22)
                            ) {
                                long dealTime = Date_Util.getSubTime(result.getCreateTime(), result.getDealTiming(), 1);
                                if (dealTime == -1) {
                                    result.setDealTime(0L);
                                } else {
                                    result.setDealTime(dealTime);
                                }
                            }
                        }
                        // 服务站拒单后区域服务经理改派后，旧工单看到的还是“服务商已拒单”拒单状态
                        if (3 == OrderStatus) {
                            List<Integer> statusList = workOrderListDao.getprocessStatusByOrderId(result.getOrderId());
                            if (statusList != null && statusList.size() > 0) {
                                if (statusList.contains(3) && (statusList.contains(5))) {
                                    result.setOrderStatus("服务商已拒单");
                                    result.setOrderStatusNo(5);
                                }
                            }
                        }
                    }
                }

                /**
                 * 3.1.0 4.2需求修改了DBU、XCEC服务工单技师维修完成后显示的处理时长
                 */
                try {
                    addHandleTimeNew(resultList);
                } catch (Exception e) {
                    log.error("getManagerOrderList->服务工单处理时长异常", e);
                }

                long et = System.currentTimeMillis() - st;
                log.info(String.format("dcec和xcec服务经理列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }

    /**
     * 客户服务经理获取列表
     *
     * @param map
     * @return
     */
    @Override
    public ModelAndView getCusManagerOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //处理当前登录账户Id，
            String UserId = map.get("UserId").toString();
            UserT ut = UserThreadLocal.get();
            long lUserId = ut.getId();
            map.put("UserId", lUserId);
            String Phone = ut.getPhone();
            map.put("Phone", Phone);
            //获取客户服务经理是那个JV的
            map.put("CompanyId", ut.getCompanyId());
            //获取ccec在企业表中主键id
            CompanyT ccecCompany = companyTDao.getCompanyInfoByCompanyNo("CCEC");
            map.put("ccecCompanyId", ccecCompany.getId());
            map.put("dbuCompanyId", 1);
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//                page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0,8,13,14,15,16";   //2.8.0ccec400主管增加14,15,16
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }

                //获取当前系统时间
                map.put("nowTime", LocalTimeUtil.getRealCurrentTime());
                //当前时间前24小时
                map.put("twentyTime", LocalTimeUtil.minusHoursToTime(24));
                //当前时间前8小时
                map.put("eightTime", LocalTimeUtil.minusHoursToTime(8));
                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    resultList = workOrderListDao.getNewCusManagerOrderList(map);
                } else {
                    resultList = workOrderListDao.getCusManagerOrderList(map);
                    //查询cds工单
                    this.getDRWorkOrderByOrderIdNew(resultList);
                    if (CollectionUtils.isNotEmpty(resultList)) {
                        WorkOrderInfo result = resultList.get(0);
                        WorkOrderInfo diagnose = diagnoseConclusionTDao.getDiagnoseByOrderId(result.getOrderId());
                        if(null != diagnose){
                            result.setFaultSolution(diagnose.getFaultSolution());
                            result.setInvalidModel(diagnose.getInvalidModel());
                            result.setProblemLevel(diagnose.getProblemLevel());
                        }
                    }
                }
                //循环处理查询列表（审核不通过、已取消、异常关闭、待用户评价 ,服务商已拒单，服务完成
                // 待用户评价-400远程解决 28，400已关闭 29，取消中 30，异常关闭申请中  31
                // 这几种情况下，处理时长=这几种动作发生时间-工单生成时间）
                if (CollectionUtils.isNotEmpty(resultList)) {
                    List<Long> orderIdList = resultList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //服务站关系类型
                    List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);
                    //获取工单收藏
                    List<WorkOrderInfo> favorateList = workOrderListDao.getFavorateByOrderIdList(orderIdList,lUserId);
                    //获取用户姓名
                    List<WorkOrderInfo> qyEngineerNameList = workOrderOperatorRelationDao.getOperatorByOrderIdList(orderIdList);
                    //获取主动升级工单
                    List<WorkOrderInfo> escalationList = escalationOrderTDao.getEscalationByOrderIdList(orderIdList);

                    for (WorkOrderInfo result : resultList) {
                        if (StringUtils.isEmpty(result.getRealESN())) {
                            result.setRealESN(result.getESN());
                        }
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        if(orderStatusNo == 30){
                            orderStatusNo = 15;
                        }
                        for(DictionariesT dict : orderStatusList){
                            if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        if(result.getOrderChannel() == 4 && result.getIsTechSupport() == 1 && orderStatusNo ==  2){
                            result.setOrderStatus("待大区经理确认");
                        }
                        //获取工单收藏
                        for(WorkOrderInfo favorate : favorateList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setIsCollect(1);
                            }
                        }
                        //获取用户姓名
                        for(WorkOrderInfo qyEngineerName : qyEngineerNameList){
                            if(result.getOrderId().equals(qyEngineerName.getOrderId())){
                                result.setQyEngineerName(qyEngineerName.getQyEngineerName());
                            }
                        }
                        //服务站关系类型
                        boolean isPrin = false;
                        for(Long orderId : principalList){
                            if(result.getOrderId().equals(orderId)){
                                isPrin = true;
                            }
                        }
                        if(isPrin){
                            if(!result.getStationRelationType().equals(2)){
                                result.setStationRelationType(1);
                            }
                        } else {
                            result.setStationRelationType(0);
                        }
                        //获取主动升级工单
                        for(WorkOrderInfo favorate : escalationList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setEscalationOrderID(favorate.getId());
                            }
                        }

                        if (ut.getCompanyId() == ccecCompany.getId()) { //当前角色是ccec渠道的  这里加层判断   如果服务站热线是空的就返回ccec渠道电话
                            if (StringUtils.isEmpty(result.getHotlineTel())) {
                                result.setHotlineTel("400-889-9990");
                            }
                        }
                        Integer OrderStatus = result.getOrderStatusNo();
                        if (null != OrderStatus) {
                            //审核不通过
                            if (OrderStatus.equals(3) || OrderStatus.equals(15)
                                    || OrderStatus.equals(13) || OrderStatus.equals(16)
                                    || OrderStatus.equals(5) || OrderStatus.equals(14)
                                    || OrderStatus.equals(28) || OrderStatus.equals(29)
                                    || OrderStatus.equals(30)
                                    || OrderStatus.equals(31)
                                    || OrderStatus.equals(20) || OrderStatus.equals(21)
                                    || OrderStatus.equals(22)
                            ) {
                                long dealTime = Date_Util.getSubTime(result.getCreateTime(), result.getDealTiming(), 1);
                                if (dealTime == -1) {
                                    result.setDealTime(0L);
                                } else {
                                    result.setDealTime(dealTime);
                                }
                            }
                        }
                    }
                }


                /**
                 * 3.1.0 4.2需求修改了DBU、XCEC服务工单技师维修完成后显示的处理时长
                 */
                try {
                    addHandleTimeNew(resultList);
                } catch (Exception e) {
                    log.error("getCusManagerOrderList->服务工单处理时长异常", e);
                }

                long et = System.currentTimeMillis() - st;
                log.info(String.format("dcec客户服务经理和xcec的服务总监列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }

    /**
     * 商务处主任获取工单列表
     */
    @Override
    public ModelAndView getDepartmentOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //处理当前登录账户Id，
            //String UserId = map.get("UserId").toString();
			/*UserT ut = new UserT();
			ut = loginDao.getUserByid(UserId);*/
            UserT ut = UserThreadLocal.get();
            long companyId = ut.getCompanyId();
            map.put("companyId", companyId);
            long lUserId = ut.getId();
            map.put("UserId", lUserId);
            String Phone = ut.getPhone();
            map.put("Phone", Phone);
            map.put("UserPhone", Phone);
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//				page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0,8,9";
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }
                //首先查询该商务处主任手下有几个服务站（服务站ID是啥）
                map.put("Level", 2);//level=2  表示商务处主任
                List<Map<String, Object>> stationList = workOrderListDao.getManagerHasStations(map);
                if(CollectionUtils.isNotEmpty(stationList)){
                    List<Long> stationIds = new ArrayList<>();
                    for (Map<String, Object> mmap : stationList) {
                        stationIds.add(MapUtils.getLong(mmap,"serviceStationId"));
                    }
                    map.put("stationIds", stationIds);
                } else {
                    JSONObject jb = new JSONObject();
                    obj.put("status", -16);
                    obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-16));
                    obj.put("data", jb);
                    //返回客户
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                    return null;
                }
                //获取当前系统时间
                map.put("nowTime", LocalTimeUtil.getRealCurrentTime());
                //当前时间前8小时
                map.put("eightTime", LocalTimeUtil.minusHoursToTime(8));
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    resultList = workOrderListDao.getNewDepartmentOrderList(map);
                } else {
                    resultList = workOrderListDao.getDepartmentOrderList(map);
                }
                //循环处理查询列表（审核不通过、已取消、异常关闭、待用户评价 这几种情况下，处理时长=这几种动作发生时间-工单生成时间）
                if (CollectionUtils.isNotEmpty(resultList)) {
                    List<Long> orderIdList = resultList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //获取工单收藏
                    List<WorkOrderInfo> favorateList = workOrderListDao.getFavorateByOrderIdList(orderIdList, lUserId);
                    //服务站关系类型
                    List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);
                    for (WorkOrderInfo result : resultList) {
                        if (StringUtils.isEmpty(result.getRealESN())) {
                            result.setRealESN(result.getESN());
                        }
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        for (DictionariesT dict : orderStatusList) {
                            if (dict.getDInt().equals(String.valueOf(orderStatusNo))) {
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        if(result.getOrderChannel() == 4 && result.getIsTechSupport() == 1 && orderStatusNo ==  2){
                            result.setOrderStatus("待大区经理确认");
                        }
                        //获取工单收藏
                        for (WorkOrderInfo favorate : favorateList) {
                            if (result.getOrderId().equals(favorate.getOrderId())) {
                                result.setIsCollect(1);
                            }
                        }
                        //服务站关系类型
                        boolean isPrin = false;
                        for (Long orderId : principalList) {
                            if (result.getOrderId().equals(orderId)) {
                                isPrin = true;
                            }
                        }
                        if (isPrin) {
                            if (!result.getStationRelationType().equals(2)) {
                                result.setStationRelationType(1);
                            }
                        } else {
                            result.setStationRelationType(0);
                        }
                        Integer OrderStatus = result.getOrderStatusNo();
                        if (null != OrderStatus) {
                            //审核不通过
                            if (OrderStatus.equals(3) || OrderStatus.equals(15)
                                    || OrderStatus.equals(13) || OrderStatus.equals(16)
                                    || OrderStatus.equals(5)
                                    || OrderStatus.equals(14)) {
                                long dealTime = Date_Util.getSubTime(result.getCreateTime(), result.getDealTiming(), 1);
                                if (dealTime == -1) {
                                    result.setDealTime(0L);
                                } else {
                                    result.setDealTime(dealTime);
                                }
                            }
                        }
                        // 服务站拒单后区域服务经理改派后，旧工单看到的还是“服务商已拒单”拒单状态
                        if (3 == OrderStatus) {
                            List<Integer> statusList = workOrderListDao.getprocessStatusByOrderId(result.getOrderId());
                            if (statusList != null && statusList.size() > 0) {
                                if (statusList.contains(3) && (statusList.contains(5))) {
                                    result.setOrderStatus("服务商已拒单");
                                    result.setOrderStatusNo(5);
                                }
                            }
                        }
                    }
                }

                /**
                 * 3.1.0 4.2需求修改了DBU、XCEC服务工单技师维修完成后显示的处理时长
                 */
                try {
                    addHandleTimeNew(resultList);
                } catch (Exception e) {
                    log.error("getDepartmentOrderList->服务工单处理时长异常", e);
                }


                long et = System.currentTimeMillis() - st;
                log.info(String.format("dcec商务处主任和xcec大区经理列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }

    //区域工程师获取工单列表(DBU)
    @Override
    public ModelAndView getDistrictEngineerOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //处理当前登录账户Id，
            UserT ut = UserThreadLocal.get();
            long companyId = ut.getCompanyId();
            map.put("companyId", companyId);
            map.put("UserId", ut.getId());
            long lUserId = ut.getId();
            map.put("Phone", ut.getPhone());
            map.put("UserPhone", ut.getPhone());
            String eAppVersion = MapUtils.getString(map,"eAppVersion");
            //处理分页信息
            int page = 1;
            if (map.get("page") != null) {
//                page = MapUtils.getInteger(map, "page", 1);
                page = MapUtils.getInteger(map, "page", 1);

            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0,8,11"; //全部,超时工单,待处理
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }
                //首先查询该区域工程师手下有几个服务站（服务站ID是啥）
                map.put("Level", 1);//level=1 表示区域工程师
                List<Map<String, Object>> stationList = new ArrayList<>();
                //如果区域工程师不属于企业用户
                if (!NumberUtils.isPositiveNum(ut.getCompanyId())) {
                    map.put("companyId", 1L);
                    stationList = workOrderListDao.getChannelStationsByEngineerPhone(map);
                } else {
                    map.put("companyId", ut.getCompanyId());
                    stationList = workOrderListDao.getManagerHasStations(map);
                }

                if(CollectionUtils.isNotEmpty(stationList)){
                    List<Long> stationIds = new ArrayList<>();
                    for (Map<String, Object> mmap : stationList) {
                        stationIds.add(MapUtils.getLong(mmap,"serviceStationId"));
                    }
                    if (stationIds.size() > 0) {
                        map.put("stationIds", stationIds);
                    }
                }
                //获取当前系统时间
                map.put("nowTime", LocalTimeUtil.getRealCurrentTime());
                //当前时间前24小时
                map.put("twentyTime", LocalTimeUtil.minusHoursToTime(24));
                List<WorkOrderInfo> resultList = new ArrayList<>();
                //如果前端没有传OrderId    则代表是请求列表
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                String dbuStatusCheck = appVersionTDao.getVersionCompatible("dbuStatusCheck");
                //分页处理，显示当前页的20条数据
                PageHelper.startPage(page, pagesize);
                if (!map.containsKey("OrderId")) {    //获取工单列表优化    目前获取工单列表和详情拆开逻辑    列表重写一个sql
                    long start = System.currentTimeMillis();
                    resultList = workOrderListDao.getNewDistrictEngineerOrderList(map);
                    long end = System.currentTimeMillis();
                    log.info("sql执行时间为：" + (end - start));
                } else {
                    long start = System.currentTimeMillis();
                    resultList = workOrderListDao.getDistrictEngineerOrderList(map);
                    //查询cds工单
                    getDRWorkOrderByOrderIdNew(resultList);
                    long end = System.currentTimeMillis();
                    log.info("sql执行时间为：" + (end - start));
                    if (CollectionUtils.isNotEmpty(resultList)) {
                        WorkOrderInfo result = resultList.get(0);
                        WorkOrderInfo diagnose = diagnoseConclusionTDao.getDiagnoseByOrderId(result.getOrderId());
                        if(null != diagnose){
                            result.setFaultSolution(diagnose.getFaultSolution());
                            result.setInvalidModel(diagnose.getInvalidModel());
                            result.setProblemLevel(diagnose.getProblemLevel());
                        }
                    }
                }

                handleFieldsNew(resultList);

                //循环处理查询列表（挂号失败,审核不通过、已取消、异常关闭、待用户评价 这几种情况下，处理时长=这几种动作发生时间-工单生成时间）
                if (CollectionUtils.isNotEmpty(resultList)) {
                    List<Long> orderIdList = resultList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //获取工单收藏
                    List<WorkOrderInfo> favorateList = workOrderListDao.getFavorateByOrderIdList(orderIdList,lUserId);
                    //获取主动升级工单
                    List<WorkOrderInfo> escalationList = escalationOrderTDao.getEscalationByOrderIdList(orderIdList);
                    //服务站关系类型
                    List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);

                    for (WorkOrderInfo result : resultList) {
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        if(orderStatusNo == 40 && (StringUtils.isBlank(eAppVersion) || eAppVersion.compareTo(dbuStatusCheck) < 0)){
                            orderStatusNo = 1;
                        }
                        for(DictionariesT dict : orderStatusList){
                            if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        //获取工单收藏
                        for(WorkOrderInfo favorate : favorateList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setIsCollect(1);
                            }
                        }
                        //获取主动升级工单
                        for(WorkOrderInfo favorate : escalationList){
                            if(result.getOrderId().equals(favorate.getOrderId())){
                                result.setEscalationOrderID(favorate.getId());
                            }
                        }
                        //服务站关系类型
                        boolean isPrin = false;
                        for(Long orderId : principalList){
                            if(result.getOrderId().equals(orderId)){
                                isPrin = true;
                            }
                        }
                        if(isPrin){
                            if(!result.getStationRelationType().equals(2)){
                                result.setStationRelationType(1);
                            }
                        } else {
                            result.setStationRelationType(0);
                        }

                        Integer OrderStatus = result.getOrderStatusNo();
                        if (null != OrderStatus) {
                            //审核不通过
                            if (OrderStatus.equals(3) || OrderStatus.equals(15)
                                    || OrderStatus.equals(13) || OrderStatus.equals(16)
                                    || OrderStatus.equals(5) || OrderStatus.equals(14)
                                    || OrderStatus.equals(20) || OrderStatus.equals(21)
                                    || OrderStatus.equals(22) || OrderStatus.equals(39)) {
                                long dealTime = Date_Util.getSubTime(result.getCreateTime(), result.getDealTiming(), 1);
                                if (dealTime == -1) {
                                    result.setDealTime(0L);
                                } else {
                                    result.setDealTime(dealTime);
                                }
                            }
                        }
                    }
                }


                /**
                 * 3.1.0 4.2需求修改了DBU、XCEC服务工单技师维修完成后显示的处理时长
                 */
                try {
                    addHandleTimeNew(resultList);
                } catch (Exception e) {
                    log.error("getDistrictEngineerOrderList->服务工单处理时长异常", e);
                }


                // 拼装是否需要补拍逻辑
                getRemedyInfoNew(MapUtils.getString(map, "OrderId"), resultList);
                long et = System.currentTimeMillis() - st;
                log.info(String.format("区域工程师(DBU)列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(resultList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }

    //服务工单经理获取工单列表(DBU)
    @Override
    public ModelAndView getWorkOrderManagerOrderList(Map<String, Object> map) {
        long st = System.currentTimeMillis();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            //处理当前登录账户Id，
            UserT ut = UserThreadLocal.get();
            map.put("companyId", ut.getCompanyId());
            map.put("UserId", ut.getId());
            long lUserId = ut.getId();
            map.put("Phone", ut.getPhone());
            map.put("UserPhone", ut.getPhone());
            String eAppVersion = MapUtils.getString(map,"eAppVersion");
            //获取系统当前时间
            map.put("nowTime", LocalTimeUtil.getRealCurrentTime());
            //查看 查询类型是否在该角色类型内
            String OrderTypeStr = "0"; //全部
            if (OrderTypeStr.contains(map.get("OrderType").toString())) {
                //处理查询参数
                if (!"".equals(MapUtils.getString(map, "OrderId", ""))) {
                    map.remove("keyword");
                } else {
                    if (!"".equals(MapUtils.getString(map, "keyword", ""))) {
                        String keyWord = map.get("keyword").toString().trim();
                        map.put("keyword", keyWord);
                    }
                }
                if (!map.containsKey("OrderId") && !map.containsKey("regionId")) {
                    obj.put("status", SMSEnum.type17.getIndex());
                    obj.put("msg", SMSEnum.type17.getName());
                    obj.put("data", "");
                    //返回客户
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                    return null;
                }
                String orderIdStr = MapUtils.getString(map, "OrderId", "");
                String regionIdStr = MapUtils.getString(map, "regionId", "");
                List<WorkOrderInfo> workOrderList = new ArrayList<>();
                //工单状态字典列表
                List<DictionariesT> orderStatusList = dictionariesTDao.getDictListByDTableName("OrderStatus");
                String dbuStatusCheck = appVersionTDao.getVersionCompatible("dbuStatusCheck");
                //分页处理，显示当前页的20条数据
                if (StringUtils.isNotEmpty(regionIdStr)) {
                    //处理分页信息
                    int page = 1;
                    if (map.get("page") != null) {
//                        page = MapUtils.getInteger(map, "page", 1);
                        page = MapUtils.getInteger(map, "page", 1);
                    }
                    int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
                    long regionId = MapUtils.getLongValue(map, "regionId"); //区域主键id
                    String levelOneIds = ""; //一级区域主键id
                    List<Map<String, Object>> levelOneRegionList = businessRegionTDao
                            .getLevelOneRegionListByParentRegionId(regionId);
                    if (CollectionUtils.isNotEmpty(levelOneRegionList)) {
                        for (Map<String, Object> levelOneRegion : levelOneRegionList) {
                            long levelOnId = MapUtils.getLongValue(levelOneRegion, "ID");
                            levelOneIds += levelOnId + ",";
                        }
                        levelOneIds = levelOneIds.substring(0, levelOneIds.length() - 1);
                    }
                    if (StringUtils.isNotEmpty(levelOneIds)) {
                        List<String> stringList = StringToool.getStringList(levelOneIds, ",");
                        List<String> serviceStationIdList = businessRegionTDao
                                .getServiceStationIdListByLevelOneRegionList(stringList);
                        if (CollectionUtils.isNotEmpty(serviceStationIdList)) {
                            map.put("stationIds", serviceStationIdList);
                        } else {
                            JSONObject jb = new JSONObject();
                            obj.put("status", -16);
                            obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-16));
                            obj.put("data", jb);
                            //返回客户
                            ParameterTool.writeResponse(response, obj.toString());
                            obj = null;
                            return null;
                        }
                        //分页处理，显示当前页的20条数据
                        PageHelper.startPage(page, pagesize);
                        workOrderList = workOrderListDao.getWorkOrderManagerOrderList(map);
                    } else {
                        JSONObject jb = new JSONObject();
                        obj.put("status", -16);
                        obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-16));
                        obj.put("data", jb);
                        //返回客户
                        ParameterTool.writeResponse(response, obj.toString());
                        obj = null;
                        return null;
                    }
                }

                if (StringUtils.isNotEmpty(orderIdStr)) {
                    workOrderList = workOrderListDao.getWorkOrderManagerOrderById(map);
                    //查询cds工单
                    getDRWorkOrderByOrderIdNew(workOrderList);
                    if (CollectionUtils.isNotEmpty(workOrderList)) {
                        WorkOrderInfo result = workOrderList.get(0);
                        WorkOrderInfo diagnose = diagnoseConclusionTDao.getDiagnoseByOrderId(result.getOrderId());
                        if(null != diagnose){
                            result.setFaultSolution(diagnose.getFaultSolution());
                            result.setInvalidModel(diagnose.getInvalidModel());
                            result.setProblemLevel(diagnose.getProblemLevel());
                        }
                    }
                }
                //循环处理查询列表（审核不通过、已取消、异常关闭、待用户评价 这几种情况下，处理时长=这几种动作发生时间-工单生成时间）
                if (CollectionUtils.isNotEmpty(workOrderList)) {
                    List<Long> orderIdList = workOrderList.stream().map(WorkOrderInfo::getOrderId).filter(a -> null != a).collect(Collectors.toList());
                    //服务站关系类型
                    List<Long> principalList = workOrderPrincipalTDao.getPrincipalByOrderIdList(orderIdList);
                    //获取用户姓名
                    List<WorkOrderInfo> qyEngineerNameList = workOrderOperatorRelationDao.getOperatorByOrderIdList(orderIdList);
                    for (WorkOrderInfo result : workOrderList) {
                        //状态转换
                        int orderStatusNo = result.getOrderStatusNo();
                        if(orderStatusNo == 40 && (StringUtils.isBlank(eAppVersion) || eAppVersion.compareTo(dbuStatusCheck) < 0)){
                            orderStatusNo = 1;
                        }
                        for(DictionariesT dict : orderStatusList){
                            if(dict.getDInt().equals(String.valueOf(orderStatusNo))){
                                result.setOrderStatus(dict.getDvalue());
                            }
                        }
                        //获取用户姓名
                        for(WorkOrderInfo qyEngineerName : qyEngineerNameList){
                            if(result.getOrderId().equals(qyEngineerName.getOrderId())){
                                result.setQyEngineerName(qyEngineerName.getQyEngineerName());
                            }
                        }
                        //服务站关系类型
                        boolean isPrin = false;
                        for(Long orderId : principalList){
                            if(result.getOrderId().equals(orderId)){
                                isPrin = true;
                            }
                        }
                        if(isPrin){
                            if(!result.getStationRelationType().equals(2)){
                                result.setStationRelationType(1);
                            }
                        } else {
                            result.setStationRelationType(0);
                        }
                        Integer OrderStatus = result.getOrderStatusNo();
                        if (null != OrderStatus) {
                            //审核不通过
                            if (OrderStatus.equals(3) || OrderStatus.equals(15)
                                    || OrderStatus.equals(13) || OrderStatus.equals(16)
                                    || OrderStatus.equals(5) || OrderStatus.equals(14)
                                    || OrderStatus.equals(20) || OrderStatus.equals(21)
                                    || OrderStatus.equals(22) || OrderStatus.equals(39)) {
                                long dealTime = Date_Util.getSubTime(result.getCreateTime(), result.getDealTiming(), 1);
                                if (dealTime == -1) {
                                    result.setDealTime(0L);
                                } else {
                                    result.setDealTime(dealTime);
                                }
                            }
                        }
                    }
                }

                /**
                 * 3.1.0 4.2需求修改了DBU、XCEC服务工单技师维修完成后显示的处理时长
                 */
                try {
                    addHandleTimeNew(workOrderList);
                } catch (Exception e) {
                    log.error("getWorkOrderManagerOrderList->服务工单处理时长异常", e);
                }

                long et = System.currentTimeMillis() - st;
                log.info(String.format("服务工单经理(DBU)列表响应消耗时间: %d", et));
                //返回数据
                JSONObject jb = new JSONObject();
                PageInfo<WorkOrderInfo> pageInfo = new PageInfo<>(workOrderList);
                jb.put("functions", JSON.toJSON(pageInfo.getList()));
                obj.put("status", SMSEnum.type0.getIndex());
                obj.put("msg", SMSEnum.type0.getName());
                obj.put("data", jb);
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else {
                //缺少必要参数
                obj.put("status", SMSEnum.type28.getIndex());
                obj.put("msg", SMSEnum.type28.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e.getMessage(), e);
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }


    /**
     * 3.1.0
     * 4.2需求修改DBU、XCEC一些角色展示服务工单在技师维修完成后的处理总时长
     * 由原来的 处理时长 = 工单服务完成时间 - 工单的创建时间
     * 改为     处理时长 = 工单待用户评价时间 - 工单的创建时间
     * 特殊说明：查有些工单在服务技师点击维修完成后，不会进入待用户评价状态(因为当前用户并非e路app终端用户)，
     * 而是直接服务完成状态，此时 处理时长 = 服务完成时间 - 工单创建时间
     *
     * @param workOrderList
     */
    private void addHandleTime(List<Map<String, Object>> workOrderList) {

        if (CollectionUtils.isNotEmpty(workOrderList)) {

            // 先过滤出工单状态为服务完成并且渠道为DBU或者XCEC的，然后在按工单id进行分组
            // key=OrderId  value=WorkOrder
            Map<Long, Map<String, Object>> kvMap = new HashMap<>();
            workOrderList.forEach(wo -> {
                if (MapUtils.getIntValue(wo, "OrderStatusNo") == 14 && (MapUtils.getIntValue(wo, "OrderChannel") == 1 || MapUtils.getIntValue(wo, "OrderChannel") == 4)) {
                    Long orderId = MapUtils.getLong(wo, "OrderId");
                    kvMap.put(orderId, wo);
                }
            });

            // 如果存在状态为服务完成的服务工单，
            // 那么设置工单的 处理时长 = （待用户评介时间/服务完成时间） - 工单创建时间
            if (MapUtils.isNotEmpty(kvMap)) {
                // key=OrderId   value=服务技师维修的完成时间
                Map<Long, Map<String, Object>> finishedTimeMap = workOrderListDao.getRepairFinishedTimeForServiceFinishedByOrderIds(new ArrayList<>(kvMap.keySet()));

                for (Entry<Long, Map<String, Object>> kv : kvMap.entrySet()) {
                    Long orderId = kv.getKey();
                    Map<String, Object> orderMap = kv.getValue();

                    // 如果查询到技师的维修完成时间时替换DealTime(处理时长),否则不替换
                    if (MapUtils.isNotEmpty(finishedTimeMap) && finishedTimeMap.containsKey(orderId)) {

                        Map<String, Object> orderFinishedTimeMap = finishedTimeMap.get(orderId);
                        // 获取技师维修完成时间
                        String finishedTime = MapUtils.getString(orderFinishedTimeMap, "FinishedTime");
                        // 工单创建时间
                        String orderCreateTime = MapUtils.getString(orderMap, "CreateTime");
                        // 计算出处理时长 单位：秒
                        long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, finishedTime);
                        orderMap.put("DealTime", seconds);
                        continue;
                    }

                    log.error(String.format("addHandleTime->未找到服务工单ID为：%d的维修完成时间", orderId));
                }
            }
        }
    }

    /**
     * 3.1.0
     * 4.2需求修改DBU、XCEC一些角色展示服务工单在技师维修完成后的处理总时长
     * 由原来的 处理时长 = 工单服务完成时间 - 工单的创建时间
     * 改为     处理时长 = 工单待用户评价时间 - 工单的创建时间
     * 特殊说明：查有些工单在服务技师点击维修完成后，不会进入待用户评价状态(因为当前用户并非e路app终端用户)，
     * 而是直接服务完成状态，此时 处理时长 = 服务完成时间 - 工单创建时间
     *
     * @param workOrderList
     */
    private void addHandleTimeNew(List<WorkOrderInfo> workOrderList) {

        if (CollectionUtils.isNotEmpty(workOrderList)) {

            // 先过滤出工单状态为服务完成并且渠道为DBU或者XCEC的，然后在按工单id进行分组
            // key=OrderId  value=WorkOrder
            Map<Long, WorkOrderInfo> kvMap = new HashMap<>();
            workOrderList.forEach(wo -> {
                if (wo.getOrderStatusNo() == 14 && (wo.getOrderChannel() == 1 || wo.getOrderChannel() == 4)) {
                    Long orderId = wo.getOrderId();
                    kvMap.put(orderId, wo);
                }
            });

            // 如果存在状态为服务完成的服务工单，
            // 那么设置工单的 处理时长 = （待用户评介时间/服务完成时间） - 工单创建时间
            if (MapUtils.isNotEmpty(kvMap)) {
                // key=OrderId   value=服务技师维修的完成时间
                Map<Long, Map<String, Object>> finishedTimeMap = workOrderListDao.getRepairFinishedTimeForServiceFinishedByOrderIds(new ArrayList<>(kvMap.keySet()));

                for (Entry<Long, WorkOrderInfo> kv : kvMap.entrySet()) {
                    Long orderId = kv.getKey();
                    WorkOrderInfo orderMap = kv.getValue();

                    // 如果查询到技师的维修完成时间时替换DealTime(处理时长),否则不替换
                    if (MapUtils.isNotEmpty(finishedTimeMap) && finishedTimeMap.containsKey(orderId)) {

                        Map<String, Object> orderFinishedTimeMap = finishedTimeMap.get(orderId);
                        // 获取技师维修完成时间
                        String finishedTime = MapUtils.getString(orderFinishedTimeMap, "FinishedTime");
                        // 工单创建时间
                        String orderCreateTime = orderMap.getCreateTime();
                        // 计算出处理时长 单位：秒
                        long seconds = LocalTimeUtil.getDurationSeconds(orderCreateTime, finishedTime);
                        orderMap.setDealTime(seconds);
                        continue;
                    }

                    log.error(String.format("addHandleTime->未找到服务工单ID为：%d的维修完成时间", orderId));
                }
            }
        }
    }

    @Override
    public void getWorkListForMT(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        Map<String, Object> data = new HashMap<>(1);

        Integer pageNo = MapUtils.getInteger(map, "page", 1);
        Integer defaultPageCount = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
        Integer pageCount = MapUtils.getInteger(map, "pageSize", defaultPageCount);
        String keyword = MapUtils.getString(map, "keyword");
        PageHelper.startPage(pageNo, pageCount, true);
        List<WorkOrderT> workOrderTList = workOrderTDao.selectListByStationAndStatus(1L, userT.getServiceStationID(),
                Dictionaries.OrderStatus_06.getIndex(), keyword);
        PageInfo pageInfo = new PageInfo<>(workOrderTList);
        data.put("total", pageInfo.getTotal());
        data.put("page", pageNo);
        List<Map<String, Object>> workList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(pageInfo.getList())) {
            ServiceStationT serviceStationT = serviceStationDao
                    .findServiceStationByID(String.valueOf(userT.getServiceStationID()));
            if (null != serviceStationT) {
                for (Object obj : pageInfo.getList()) {
                    WorkOrderT workOrderT = (WorkOrderT) obj;
                    Map<String, Object> orderResponse = new HashMap<>();
                    orderResponse.put("orderId", workOrderT.getId());
                    orderResponse.put("orderNo", workOrderT.getOrderNo());
                    orderResponse.put("ESN", workOrderT.getESN());
                    orderResponse.put("OEM", workOrderT.getoEMName());
                    orderResponse.put("OEMId", workOrderT.getoEMID());
                    orderResponse.put("marketType", workOrderT.getMarketType());
                    orderResponse.put("application", workOrderT.getApplication());

                    orderResponse.put("createTime", workOrderT.getCreateTime());
                    orderResponse.put("faultDesc", workOrderT.getCustomerComplaint());
                    // 经销商地点
                    orderResponse.put("stationLon", serviceStationT.getPositionLon());
                    orderResponse.put("stationLat", serviceStationT.getPositionLat());
                    orderResponse.put("stationLocation", serviceStationT.getAddress());
                    // 维修地点
                    orderResponse.put("repairLon", workOrderT.getLocLon());
                    orderResponse.put("repairLat", workOrderT.getLocLat());
                    orderResponse.put("repairLocation", workOrderT.getLocation());
                    // 服务工单来源
                    orderResponse.put("orderSource", workOrderT.getOrderSource());
                    workList.add(orderResponse);
                }
            }
        }
        data.put("list", workList);
        ParameterTool.writeSuccessResponse(response, data);
    }

    @Override
    public Map<String, Object> getMaxOrderId(String time) {
        // TODO Auto-generated method stub
        Map<String, Object> map = workOrderListDao.getMaxOrderId(time);
        return map;
    }

    private void getRemedyInfo(String orderId, List<Map<String, Object>> orderMapList) {
        //理论上，orderId不为空，并且工单列表不为空，说明为详情访问
        if (StringUtils.isNotEmpty(orderId) && CollectionUtils.isNotEmpty(orderMapList)) {
            Map<String, Object> orderMap = orderMapList.get(0);
            int remedyCount = workOrderRemedyPictureDao.selectCountByOrderId(Long.valueOf(orderId));
            if (NumberUtils.isPositiveNum(remedyCount)) {
                orderMap.put("needRemedy", 1);
            } else {
                orderMap.put("needRemedy", 0);
            }
        }
    }

    private void getRemedyInfoNew(String orderId, List<WorkOrderInfo> orderMapList) {
        //理论上，orderId不为空，并且工单列表不为空，说明为详情访问
        if (StringUtils.isNotEmpty(orderId) && CollectionUtils.isNotEmpty(orderMapList)) {
            WorkOrderInfo orderMap = orderMapList.get(0);
            int remedyCount = workOrderRemedyPictureDao.selectCountByOrderId(Long.valueOf(orderId));
            if (NumberUtils.isPositiveNum(remedyCount)) {
                orderMap.setNeedRemedy(1);
            } else {
                orderMap.setNeedRemedy(0);
            }
        }
    }

    @Override
    public ModelAndView getOrderInfo(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            long orderId = MapUtils.getLongValue(map, "orderId", -1);
            if (orderId == -1) {
                obj.put("status", SMSEnum.type17.getIndex());
                obj.put("msg", SMSEnum.type17.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
            Map<String, Object> orderInfo = workOrderListDao.getMTOrderInfo(orderId);
            // 添加是否是 道路非道路
            if (StringUtils.isNotBlank(MapUtils.getString(orderInfo,"MarketType"))) {//道路
                if ("Truck 卡车".equals(MapUtils.getString(orderInfo,"MarketType"))||"Bus 客车".equals(MapUtils.getString(orderInfo,"MarketType"))) {
                    orderInfo.put("EsnApplicationType",0);
                }else {//非道路
                    orderInfo.put("EsnApplicationType",1);
                }
            }
            //查询是否cds工单
            getDRWorkOrderByOrderId(orderInfo, orderId);
            JSONObject jb = new JSONObject();
            jb.put("functions", orderInfo);
            obj.put("status", SMSEnum.type0.getIndex());
            obj.put("msg", SMSEnum.type0.getName());
            obj.put("data", jb);
            //返回客户
            ParameterTool.writeResponse(response, obj.toString());
            obj = null;
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            // TODO: handle exception
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }



    //外部系统终端用户获取工单详情
    @Override
    public ModelAndView outSideUserGetOrderInfoById(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        JSONObject obj = new JSONObject();
        try {
            long orderId = MapUtils.getLongValue(map, "orderId", -1);
            //和前端约定好的code    这里采取orderId加密
            String code = MapUtils.getString(map, "code", "");
            if (orderId == -1 || StringUtils.isEmpty(code) || !code.equals(AESTool.encryptString(String.valueOf(orderId)))) {
                obj.put("status", SMSEnum.type17.getIndex());
                obj.put("msg", SMSEnum.type17.getName());
                obj.put("data", "");
                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
            Map<String, Object> orderInfo = workOrderListDao.outSideUserGetOrderInfoById(orderId);
            map.put("OrderId", orderId);
            //查询工单操作记录信息
            List<Map<String, Object>> timerShaftList = workOrderListDao.getWorkOrderFlowTimeList(map);
            Map<String, Object> timerShaftPublicMap = timerShaftPublic(map, timerShaftList);
            JSONObject jb = new JSONObject();
            jb.put("orderInfo", orderInfo);
            jb.put("timerShaft", timerShaftPublicMap);
            obj.put("status", SMSEnum.type0.getIndex());
            obj.put("msg", SMSEnum.type0.getName());
            obj.put("data", jb);
            //返回客户
            ParameterTool.writeResponse(response, obj.toString());
            obj = null;
            return null;
        } catch (Exception e) {
            // TODO: handle exception
            ParameterTool.writeErrorResponse(response);
            return null;
        }
    }

    @Override
    public void getWorkOrderIsExistence(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        map.get("phone");
        String OrderNo = MapUtils.getString(map, "OrderNo");
        String OrderChannel = MapUtils.getString(map, "OrderChannel");
        int num = workOrderTDao.getWorkOrderIsExistence(OrderNo, OrderChannel);
        map = new HashMap<>();
        map.put("data", num > 0);
        map.put("msg", "success");
        ParameterTool.writeResponse(response, map.toString());
    }

    @Override
    public List<ServiceStationT> querychildrenStationByFatherStationId(Long stationId) {
        return serviceStationDao.querychildrenStationByFatherStationId(stationId);
    }

    @Override
    public ServiceStationT queryFatherStationByChildrenStationId(Long stationId, String businessNo) {
        return serviceStationDao.queryFatherStationByChildrenStationId(stationId, businessNo);
    }


    //时间轴接口公用方法   map中有OrderId    list是时间轴集合
    public Map<String, Object> timerShaftPublic(Map<String, Object> map, List list) {
        String resultJson = "";
        //如果工单状态不为空，获取列表信息
        //2.8.0   保存主副技师信息返给前端
        Map<String, Object> jsMsgMap = new HashMap<>();

        if (CollectionUtils.isNotEmpty(list)) {
            //返回数据
            List<Map<String, Object>> userlist = new ArrayList<>();
            Map<String, Object> mapss = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map1 = (Map<String, Object>) list.get(i);
                Map<String, Object> mapuser = new HashMap<>();
                mapuser.put("IsOverTime", MapUtils.getIntValue(map1, "IsOverTime"));
                if (i == 0) {
                    mapss.put("stationName", map1.get("StationName"));
                    mapss.put("hotline", map1.get("HotlineTel"));
                    long orderId = Long.parseLong(map1.get("OrderId").toString());
                    Map<String, Object> workOrderMap = workOrderTDao.getOrderById(orderId);
                    mapuser.put("CreateTime", workOrderMap.get("CreateTime"));
                } else {
                    mapuser.put("CreateTime", map1.get("CreateTime"));
                }
                mapuser.put("processStatus", map1.get("processStatus"));
                mapuser.put("technicianName", map1.get("UserName"));
                mapuser.put("Phone", map1.get("Phone"));
                mapuser.put("comment", map1.get("ProcessComment"));
                if (map1.get("processStatus").toString().equals("6")) { //当工单状态为待派服务技师时
                    int isOutside = MapUtils.getInteger(map1, "IsOutside"); //1是外出   0是不外出
                    double guessDistance = MapUtils.getDouble(map1, "GuessDistance", 0D);
                    int isMoreThan = 0; //是否大于三百公里标志   1代表是   0代表否
                    if (isOutside == 1 && guessDistance >= 300) {
                        isMoreThan = 1;
                    }
                    mapuser.put("isMoreThan", isMoreThan);
                }

                if (map1.get("processStatus").toString().equals("7") || map1.get("processStatus").toString().equals("8")) {
                    //当工单状态为待服务技师接单时，把服务技师的姓名和手机号也返给前端
                    //考虑到网约技师没有待服务技师接单情况    增加8状态的判断
                    long orderid = MapUtils.getLongValue(map1, "OrderId", 0);
                    Map<String, Object> jsUser = userTDao.getUserByOrderId(orderid);
                    Map<String, Object> zjsMap = new HashMap<>();
                    if (MapUtils.isNotEmpty(jsUser)) {
                        mapuser.put("jsContact", jsUser.get("Contact"));
                        mapuser.put("jsPhone", jsUser.get("Phone"));
                        zjsMap.put("jsContact", jsUser.get("Contact"));
                        zjsMap.put("jsPhone", jsUser.get("Phone"));
                    }
                    jsMsgMap.put("zjsMsg", zjsMap);   //主技师信息

                    List<Map<String, Object>> fjsUserList = userTDao.getFuUserListByOrderId(orderid);
                    List<Map<String, Object>> fjsList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(fjsUserList)) {
                        for (Map<String, Object> fjsUser : fjsUserList) {
                            Map<String, Object> fjs = new HashMap<>();
                            fjs.put("jsContact", fjsUser.get("Contact"));
                            fjs.put("jsPhone", fjsUser.get("Phone"));
                            fjsList.add(fjs);
                        }
                    }
                    jsMsgMap.put("fjsMsg", fjsList);   //副技师信息
                }

                if (map1.get("processStatus").toString().equals("31")) { //当工单状态为异常关闭申请中时，通过操作人反查出角色，姓名，电话，返给前端
                    long creator = MapUtils.getLongValue(map1, "Creator");
                    Map<String, Object> roleNamesMap = rolesTDao.getRoleNamesByUserId(creator);
                    mapuser.put("roleNames", MapUtils.getString(roleNamesMap, "RoleNames"));
                    mapuser.put("creatorContact", MapUtils.getString(map1, "CreatorContact"));
                    mapuser.put("creatorPhone", MapUtils.getString(map1, "CreatorPhone"));
                }

                if (map1.get("processStatus").toString().equals("16")) { //当工单状态为异常关闭时，通过操作人反查出角色，姓名，电话，返给前端
                    long creator = MapUtils.getLongValue(map1, "Creator");
                    Map<String, Object> roleNamesMap = rolesTDao.getRoleNamesByUserId(creator);
                    mapuser.put("roleNames", MapUtils.getString(roleNamesMap, "RoleNames"));
                    mapuser.put("creatorContact", MapUtils.getString(map1, "CreatorContact"));
                    mapuser.put("creatorPhone", MapUtils.getString(map1, "CreatorPhone"));
                }

                // TODO 工单状态为：18/21时增加区域工程师的（姓名+电话）
                String processStatus = map1.get("processStatus").toString();
                if ("18".equals(processStatus) || "21".equals(processStatus)) {
                    // 根据服务工单id查询出服务工单对应的区域工程师
                    long orderId = MapUtils.getLongValue(map, "OrderId");
                    if (!Objects.isNull(orderId)) {
                        Map<String, Object> op = workOrderOperatorRelationDao.getOperatorByOrderId(orderId);
                        if (!Objects.isNull(op)) {
                            String name = MapUtils.getString(op, "Name");
                            String phone = MapUtils.getString(op, "Phone");
                            // 当区域工程师的姓名与手机号都不为空是返回
                            if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(phone)) {
                                mapuser.put("engName", name);
                                mapuser.put("engPhone", phone);
                            }
                        }
                    }
                }

                mapuser.put("RefuseReasonStation", MapUtils.getString(map1, "RefuseReasonStation", ""));
                mapuser.put("CloseReason", MapUtils.getString(map1, "CloseReason", ""));
                userlist.add(mapuser);
            }
            Map<String, Object> map4 = new HashMap<>();
            map4.put("stationInfo", mapss);
            map4.put("hisData", userlist);
            map4.put("jsMsg", jsMsgMap);
			/*if(CollectionUtils.isNotEmpty(oldWorkOrderList)){
				map4.put("oldWorkOrderList",oldWorkOrderList);
			}*/
            return map4;
        } else {
            return new HashMap<>();
        }
    }

    /**
     * dbu通过服务工单orderid 查询cds工单 id
     *
     * @param resultList
     */
    public void getDRWorkOrderByOrderId(List<Map<String, Object>> resultList) {
        if (CollectionUtils.isNotEmpty(resultList)) {
            Map<String, Object> objectMap = resultList.get(0);
            Long id = MapUtils.getLong(objectMap, "OrderId");
            //渠道为dbu（OrderChannel=1）
            Integer orderChannel = MapUtils.getInteger(objectMap, "OrderChannel");
            if (null != id && 1 == orderChannel) {
                Map<String, Object> drWorkOrderMap = workOrderTDao.getDRWorkOrderByOrderIdAndFlag(id);
                if (MapUtils.isNotEmpty(drWorkOrderMap)) {
                    Long drWorkOrderId = MapUtils.getLong(drWorkOrderMap, "ID");
                    objectMap.put("drWorkOrderId", drWorkOrderId);
                }
            }
        }
    }

    /**
     * dbu通过服务工单orderid 查询cds工单 id
     *
     * @param resultList
     */
    public void getDRWorkOrderByOrderIdNew(List<WorkOrderInfo> resultList) {
        if (CollectionUtils.isNotEmpty(resultList)) {
            WorkOrderInfo objectMap = resultList.get(0);
            Long id = objectMap.getOrderId();
            //渠道为dbu（OrderChannel=1）
            Integer orderChannel = objectMap.getOrderChannel();
            if (null != id && 1 == orderChannel) {
                Map<String, Object> drWorkOrderMap = workOrderTDao.getDRWorkOrderByOrderIdAndFlag(id);
                if (MapUtils.isNotEmpty(drWorkOrderMap)) {
                    Long drWorkOrderId = MapUtils.getLong(drWorkOrderMap, "ID");
                    objectMap.setDrWorkOrderId(drWorkOrderId);
                }
            }
        }
    }

    /**
     * dbu通过服务工单orderid 查询cds工单 id
     *
     * @param map
     * @param orderId
     */
    public void getDRWorkOrderByOrderId(Map<String, Object> map, Long orderId) {
        Integer orderChannel = MapUtils.getInteger(map, "OrderChannel");
        if (null != orderId && 1 == orderChannel) {
            Map<String, Object> drWorkOrderMap = workOrderTDao.getDRWorkOrderByOrderIdAndFlag(orderId);
            if (MapUtils.isNotEmpty(drWorkOrderMap)) {
                Long drWorkOrderId = MapUtils.getLong(drWorkOrderMap, "ID");
                map.put("drWorkOrderId", drWorkOrderId);
            }
        }
    }

    public static final String SEMICOLON = ";";
    public static final String COMMA = ",";
    public static final String SPOT = ".";

    /*
     * 功能描述：零件String转换list
     * @param component:
     * @Return: java.util.List<com.cci.srt.repair.model.ComponentInfo>
     * @Author: 商伟
     * @Date: 2022/7/12 11:39
     * @Description:
     */
    public static List<String> componentStringToList(String component){
        List<String> componentList = new ArrayList<>();
        if(StringUtils.isNotBlank(component)){
            component = component.substring(component.indexOf(SPOT) + 1);
            String[] componentAttr = component.split(SEMICOLON);
            if(componentAttr.length > 0){
                for (String infoStr : componentAttr) {
                    if (infoStr.indexOf(COMMA) >= 0 && infoStr.lastIndexOf(COMMA) >= 0) {
                        String[] infoAttr = infoStr.split(COMMA);
                        if(infoAttr.length >= 3){
                            String name = infoAttr[1];
                            if(StringUtils.isNotBlank(name)){
                                componentList.add(name);
                            }
                        }
                    }
                }
            }
        }

        return componentList;
    }

}
